babylon.max.js 3.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410
  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. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var MathTools = (function () {
  23. function MathTools() {
  24. }
  25. /**
  26. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  27. */
  28. MathTools.WithinEpsilon = function (a, b, epsilon) {
  29. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  30. var num = a - b;
  31. return -epsilon <= num && num <= epsilon;
  32. };
  33. /**
  34. * Returns a string : the upper case translation of the number i to hexadecimal.
  35. */
  36. MathTools.ToHex = function (i) {
  37. var str = i.toString(16);
  38. if (i <= 15) {
  39. return ("0" + str).toUpperCase();
  40. }
  41. return str.toUpperCase();
  42. };
  43. /**
  44. * Returns -1 if value is negative and +1 is value is positive.
  45. * Returns the value itself if it's equal to zero.
  46. */
  47. MathTools.Sign = function (value) {
  48. value = +value; // convert to a number
  49. if (value === 0 || isNaN(value))
  50. return value;
  51. return value > 0 ? 1 : -1;
  52. };
  53. /**
  54. * Returns the value itself if it's between min and max.
  55. * Returns min if the value is lower than min.
  56. * Returns max if the value is greater than max.
  57. */
  58. MathTools.Clamp = function (value, min, max) {
  59. if (min === void 0) { min = 0; }
  60. if (max === void 0) { max = 1; }
  61. return Math.min(max, Math.max(min, value));
  62. };
  63. return MathTools;
  64. }());
  65. BABYLON.MathTools = MathTools;
  66. var Scalar = (function () {
  67. function Scalar() {
  68. }
  69. /**
  70. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  71. */
  72. Scalar.Lerp = function (start, end, amount) {
  73. return start + ((end - start) * amount);
  74. };
  75. /**
  76. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  77. */
  78. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  79. var squared = amount * amount;
  80. var cubed = amount * squared;
  81. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  82. var part2 = (-2.0 * cubed) + (3.0 * squared);
  83. var part3 = (cubed - (2.0 * squared)) + amount;
  84. var part4 = cubed - squared;
  85. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  86. };
  87. return Scalar;
  88. }());
  89. BABYLON.Scalar = Scalar;
  90. var Color3 = (function () {
  91. /**
  92. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  93. */
  94. function Color3(r, g, b) {
  95. if (r === void 0) { r = 0; }
  96. if (g === void 0) { g = 0; }
  97. if (b === void 0) { b = 0; }
  98. this.r = r;
  99. this.g = g;
  100. this.b = b;
  101. }
  102. /**
  103. * Returns a string with the Color3 current values.
  104. */
  105. Color3.prototype.toString = function () {
  106. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  107. };
  108. /**
  109. * Returns the string "Color3".
  110. */
  111. Color3.prototype.getClassName = function () {
  112. return "Color3";
  113. };
  114. /**
  115. * Returns the Color3 hash code.
  116. */
  117. Color3.prototype.getHashCode = function () {
  118. var hash = this.r || 0;
  119. hash = (hash * 397) ^ (this.g || 0);
  120. hash = (hash * 397) ^ (this.b || 0);
  121. return hash;
  122. };
  123. // Operators
  124. /**
  125. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  126. * Returns the Color3.
  127. */
  128. Color3.prototype.toArray = function (array, index) {
  129. if (index === undefined) {
  130. index = 0;
  131. }
  132. array[index] = this.r;
  133. array[index + 1] = this.g;
  134. array[index + 2] = this.b;
  135. return this;
  136. };
  137. /**
  138. * Returns a new Color4 object from the current Color3 and the passed alpha.
  139. */
  140. Color3.prototype.toColor4 = function (alpha) {
  141. if (alpha === void 0) { alpha = 1; }
  142. return new Color4(this.r, this.g, this.b, alpha);
  143. };
  144. /**
  145. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  146. */
  147. Color3.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. /**
  153. * Returns the luminance value (float).
  154. */
  155. Color3.prototype.toLuminance = function () {
  156. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  157. };
  158. /**
  159. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  160. * Returns this new object.
  161. */
  162. Color3.prototype.multiply = function (otherColor) {
  163. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  164. };
  165. /**
  166. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  167. * Returns the current Color3.
  168. */
  169. Color3.prototype.multiplyToRef = function (otherColor, result) {
  170. result.r = this.r * otherColor.r;
  171. result.g = this.g * otherColor.g;
  172. result.b = this.b * otherColor.b;
  173. return this;
  174. };
  175. /**
  176. * Boolean : True if the rgb values are equal to the passed ones.
  177. */
  178. Color3.prototype.equals = function (otherColor) {
  179. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  180. };
  181. /**
  182. * Boolean : True if the rgb values are equal to the passed ones.
  183. */
  184. Color3.prototype.equalsFloats = function (r, g, b) {
  185. return this.r === r && this.g === g && this.b === b;
  186. };
  187. /**
  188. * Multiplies in place each rgb value by scale.
  189. * Returns the updated Color3.
  190. */
  191. Color3.prototype.scale = function (scale) {
  192. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  193. };
  194. /**
  195. * Multiplies the rgb values by scale and stores the result into "result".
  196. * Returns the unmodified current Color3.
  197. */
  198. Color3.prototype.scaleToRef = function (scale, result) {
  199. result.r = this.r * scale;
  200. result.g = this.g * scale;
  201. result.b = this.b * scale;
  202. return this;
  203. };
  204. /**
  205. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  206. */
  207. Color3.prototype.add = function (otherColor) {
  208. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  209. };
  210. /**
  211. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  212. * Returns the unmodified current Color3.
  213. */
  214. Color3.prototype.addToRef = function (otherColor, result) {
  215. result.r = this.r + otherColor.r;
  216. result.g = this.g + otherColor.g;
  217. result.b = this.b + otherColor.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  222. */
  223. Color3.prototype.subtract = function (otherColor) {
  224. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  225. };
  226. /**
  227. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  228. * Returns the unmodified current Color3.
  229. */
  230. Color3.prototype.subtractToRef = function (otherColor, result) {
  231. result.r = this.r - otherColor.r;
  232. result.g = this.g - otherColor.g;
  233. result.b = this.b - otherColor.b;
  234. return this;
  235. };
  236. /**
  237. * Returns a new Color3 copied the current one.
  238. */
  239. Color3.prototype.clone = function () {
  240. return new Color3(this.r, this.g, this.b);
  241. };
  242. /**
  243. * Copies the rgb values from the source in the current Color3.
  244. * Returns the updated Color3.
  245. */
  246. Color3.prototype.copyFrom = function (source) {
  247. this.r = source.r;
  248. this.g = source.g;
  249. this.b = source.b;
  250. return this;
  251. };
  252. /**
  253. * Updates the Color3 rgb values from the passed floats.
  254. * Returns the Color3.
  255. */
  256. Color3.prototype.copyFromFloats = function (r, g, b) {
  257. this.r = r;
  258. this.g = g;
  259. this.b = b;
  260. return this;
  261. };
  262. /**
  263. * Updates the Color3 rgb values from the passed floats.
  264. * Returns the Color3.
  265. */
  266. Color3.prototype.set = function (r, g, b) {
  267. return this.copyFromFloats(r, g, b);
  268. };
  269. /**
  270. * Returns the Color3 hexadecimal code as a string.
  271. */
  272. Color3.prototype.toHexString = function () {
  273. var intR = (this.r * 255) | 0;
  274. var intG = (this.g * 255) | 0;
  275. var intB = (this.b * 255) | 0;
  276. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  277. };
  278. /**
  279. * Returns a new Color3 converted to linear space.
  280. */
  281. Color3.prototype.toLinearSpace = function () {
  282. var convertedColor = new Color3();
  283. this.toLinearSpaceToRef(convertedColor);
  284. return convertedColor;
  285. };
  286. /**
  287. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  288. * Returns the unmodified Color3.
  289. */
  290. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  291. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  292. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  293. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  294. return this;
  295. };
  296. /**
  297. * Returns a new Color3 converted to gamma space.
  298. */
  299. Color3.prototype.toGammaSpace = function () {
  300. var convertedColor = new Color3();
  301. this.toGammaSpaceToRef(convertedColor);
  302. return convertedColor;
  303. };
  304. /**
  305. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  306. * Returns the unmodified Color3.
  307. */
  308. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  309. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  310. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  311. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  312. return this;
  313. };
  314. // Statics
  315. /**
  316. * Creates a new Color3 from the string containing valid hexadecimal values.
  317. */
  318. Color3.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  320. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  321. return new Color3(0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. return Color3.FromInts(r, g, b);
  327. };
  328. /**
  329. * Creates a new Vector3 from the startind index of the passed array.
  330. */
  331. Color3.FromArray = function (array, offset) {
  332. if (offset === void 0) { offset = 0; }
  333. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  334. };
  335. /**
  336. * Creates a new Color3 from integer values ( < 256).
  337. */
  338. Color3.FromInts = function (r, g, b) {
  339. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  340. };
  341. /**
  342. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  343. */
  344. Color3.Lerp = function (start, end, amount) {
  345. var r = start.r + ((end.r - start.r) * amount);
  346. var g = start.g + ((end.g - start.g) * amount);
  347. var b = start.b + ((end.b - start.b) * amount);
  348. return new Color3(r, g, b);
  349. };
  350. Color3.Red = function () { return new Color3(1, 0, 0); };
  351. Color3.Green = function () { return new Color3(0, 1, 0); };
  352. Color3.Blue = function () { return new Color3(0, 0, 1); };
  353. Color3.Black = function () { return new Color3(0, 0, 0); };
  354. Color3.White = function () { return new Color3(1, 1, 1); };
  355. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  356. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  357. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  358. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  359. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  360. return Color3;
  361. }());
  362. BABYLON.Color3 = Color3;
  363. var Color4 = (function () {
  364. /**
  365. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  366. */
  367. function Color4(r, g, b, a) {
  368. this.r = r;
  369. this.g = g;
  370. this.b = b;
  371. this.a = a;
  372. }
  373. // Operators
  374. /**
  375. * Adds in place the passed Color4 values to the current Color4.
  376. * Returns the updated Color4.
  377. */
  378. Color4.prototype.addInPlace = function (right) {
  379. this.r += right.r;
  380. this.g += right.g;
  381. this.b += right.b;
  382. this.a += right.a;
  383. return this;
  384. };
  385. /**
  386. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  387. */
  388. Color4.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. /**
  394. * Stores from the starting index in the passed array the Color4 successive values.
  395. * Returns the Color4.
  396. */
  397. Color4.prototype.toArray = function (array, index) {
  398. if (index === undefined) {
  399. index = 0;
  400. }
  401. array[index] = this.r;
  402. array[index + 1] = this.g;
  403. array[index + 2] = this.b;
  404. array[index + 3] = this.a;
  405. return this;
  406. };
  407. /**
  408. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  409. */
  410. Color4.prototype.add = function (right) {
  411. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  412. };
  413. /**
  414. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  415. */
  416. Color4.prototype.subtract = function (right) {
  417. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  418. };
  419. /**
  420. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  421. * Returns the Color4.
  422. */
  423. Color4.prototype.subtractToRef = function (right, result) {
  424. result.r = this.r - right.r;
  425. result.g = this.g - right.g;
  426. result.b = this.b - right.b;
  427. result.a = this.a - right.a;
  428. return this;
  429. };
  430. /**
  431. * Creates a new Color4 with the current Color4 values multiplied by scale.
  432. */
  433. Color4.prototype.scale = function (scale) {
  434. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  435. };
  436. /**
  437. * Multiplies the current Color4 values by scale and stores the result in "result".
  438. * Returns the Color4.
  439. */
  440. Color4.prototype.scaleToRef = function (scale, result) {
  441. result.r = this.r * scale;
  442. result.g = this.g * scale;
  443. result.b = this.b * scale;
  444. result.a = this.a * scale;
  445. return this;
  446. };
  447. /**
  448. * Multipy an RGBA Color4 value by another and return a new Color4 object
  449. * @param color The Color4 (RGBA) value to multiply by
  450. * @returns A new Color4.
  451. */
  452. Color4.prototype.multiply = function (color) {
  453. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  454. };
  455. /**
  456. * Multipy an RGBA Color4 value by another and push the result in a reference value
  457. * @param color The Color4 (RGBA) value to multiply by
  458. * @param result The Color4 (RGBA) to fill the result in
  459. * @returns the result Color4.
  460. */
  461. Color4.prototype.multiplyToRef = function (color, result) {
  462. result.r = this.r * color.r;
  463. result.g = this.g * color.g;
  464. result.b = this.b * color.b;
  465. result.a = this.a * color.a;
  466. return result;
  467. };
  468. /**
  469. * Returns a string with the Color4 values.
  470. */
  471. Color4.prototype.toString = function () {
  472. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  473. };
  474. /**
  475. * Returns the string "Color4"
  476. */
  477. Color4.prototype.getClassName = function () {
  478. return "Color4";
  479. };
  480. /**
  481. * Return the Color4 hash code as a number.
  482. */
  483. Color4.prototype.getHashCode = function () {
  484. var hash = this.r || 0;
  485. hash = (hash * 397) ^ (this.g || 0);
  486. hash = (hash * 397) ^ (this.b || 0);
  487. hash = (hash * 397) ^ (this.a || 0);
  488. return hash;
  489. };
  490. /**
  491. * Creates a new Color4 copied from the current one.
  492. */
  493. Color4.prototype.clone = function () {
  494. return new Color4(this.r, this.g, this.b, this.a);
  495. };
  496. /**
  497. * Copies the passed Color4 values into the current one.
  498. * Returns the updated Color4.
  499. */
  500. Color4.prototype.copyFrom = function (source) {
  501. this.r = source.r;
  502. this.g = source.g;
  503. this.b = source.b;
  504. this.a = source.a;
  505. return this;
  506. };
  507. /**
  508. * Copies the passed float values into the current one.
  509. * Returns the updated Color4.
  510. */
  511. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  512. this.r = r;
  513. this.g = g;
  514. this.b = b;
  515. this.a = a;
  516. return this;
  517. };
  518. /**
  519. * Copies the passed float values into the current one.
  520. * Returns the updated Color4.
  521. */
  522. Color4.prototype.set = function (r, g, b, a) {
  523. return this.copyFromFloats(r, g, b, a);
  524. };
  525. /**
  526. * Returns a string containing the hexadecimal Color4 code.
  527. */
  528. Color4.prototype.toHexString = function () {
  529. var intR = (this.r * 255) | 0;
  530. var intG = (this.g * 255) | 0;
  531. var intB = (this.b * 255) | 0;
  532. var intA = (this.a * 255) | 0;
  533. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  534. };
  535. // Statics
  536. /**
  537. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  538. */
  539. Color4.FromHexString = function (hex) {
  540. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  541. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  542. return new Color4(0.0, 0.0, 0.0, 0.0);
  543. }
  544. var r = parseInt(hex.substring(1, 3), 16);
  545. var g = parseInt(hex.substring(3, 5), 16);
  546. var b = parseInt(hex.substring(5, 7), 16);
  547. var a = parseInt(hex.substring(7, 9), 16);
  548. return Color4.FromInts(r, g, b, a);
  549. };
  550. /**
  551. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  552. */
  553. Color4.Lerp = function (left, right, amount) {
  554. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  555. Color4.LerpToRef(left, right, amount, result);
  556. return result;
  557. };
  558. /**
  559. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  560. */
  561. Color4.LerpToRef = function (left, right, amount, result) {
  562. result.r = left.r + (right.r - left.r) * amount;
  563. result.g = left.g + (right.g - left.g) * amount;
  564. result.b = left.b + (right.b - left.b) * amount;
  565. result.a = left.a + (right.a - left.a) * amount;
  566. };
  567. /**
  568. * Creates a new Color4 from the starting index element of the passed array.
  569. */
  570. Color4.FromArray = function (array, offset) {
  571. if (offset === void 0) { offset = 0; }
  572. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  573. };
  574. /**
  575. * Creates a new Color4 from the passed integers ( < 256 ).
  576. */
  577. Color4.FromInts = function (r, g, b, a) {
  578. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  579. };
  580. Color4.CheckColors4 = function (colors, count) {
  581. // Check if color3 was used
  582. if (colors.length === count * 3) {
  583. var colors4 = [];
  584. for (var index = 0; index < colors.length; index += 3) {
  585. var newIndex = (index / 3) * 4;
  586. colors4[newIndex] = colors[index];
  587. colors4[newIndex + 1] = colors[index + 1];
  588. colors4[newIndex + 2] = colors[index + 2];
  589. colors4[newIndex + 3] = 1.0;
  590. }
  591. return colors4;
  592. }
  593. return colors;
  594. };
  595. return Color4;
  596. }());
  597. BABYLON.Color4 = Color4;
  598. var Vector2 = (function () {
  599. /**
  600. * Creates a new Vector2 from the passed x and y coordinates.
  601. */
  602. function Vector2(x, y) {
  603. this.x = x;
  604. this.y = y;
  605. }
  606. /**
  607. * Returns a string with the Vector2 coordinates.
  608. */
  609. Vector2.prototype.toString = function () {
  610. return "{X: " + this.x + " Y:" + this.y + "}";
  611. };
  612. /**
  613. * Returns the string "Vector2"
  614. */
  615. Vector2.prototype.getClassName = function () {
  616. return "Vector2";
  617. };
  618. /**
  619. * Returns the Vector2 hash code as a number.
  620. */
  621. Vector2.prototype.getHashCode = function () {
  622. var hash = this.x || 0;
  623. hash = (hash * 397) ^ (this.y || 0);
  624. return hash;
  625. };
  626. // Operators
  627. /**
  628. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  629. * Returns the Vector2.
  630. */
  631. Vector2.prototype.toArray = function (array, index) {
  632. if (index === void 0) { index = 0; }
  633. array[index] = this.x;
  634. array[index + 1] = this.y;
  635. return this;
  636. };
  637. /**
  638. * Returns a new array with 2 elements : the Vector2 coordinates.
  639. */
  640. Vector2.prototype.asArray = function () {
  641. var result = [];
  642. this.toArray(result, 0);
  643. return result;
  644. };
  645. /**
  646. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  647. * Returns the updated Vector2.
  648. */
  649. Vector2.prototype.copyFrom = function (source) {
  650. this.x = source.x;
  651. this.y = source.y;
  652. return this;
  653. };
  654. /**
  655. * Sets the Vector2 coordinates with the passed floats.
  656. * Returns the updated Vector2.
  657. */
  658. Vector2.prototype.copyFromFloats = function (x, y) {
  659. this.x = x;
  660. this.y = y;
  661. return this;
  662. };
  663. /**
  664. * Sets the Vector2 coordinates with the passed floats.
  665. * Returns the updated Vector2.
  666. */
  667. Vector2.prototype.set = function (x, y) {
  668. return this.copyFromFloats(x, y);
  669. };
  670. /**
  671. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  672. */
  673. Vector2.prototype.add = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  678. * Returns the Vector2.
  679. */
  680. Vector2.prototype.addToRef = function (otherVector, result) {
  681. result.x = this.x + otherVector.x;
  682. result.y = this.y + otherVector.y;
  683. return this;
  684. };
  685. /**
  686. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  687. * Returns the updated Vector2.
  688. */
  689. Vector2.prototype.addInPlace = function (otherVector) {
  690. this.x += otherVector.x;
  691. this.y += otherVector.y;
  692. return this;
  693. };
  694. /**
  695. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  696. */
  697. Vector2.prototype.addVector3 = function (otherVector) {
  698. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  699. };
  700. /**
  701. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  702. */
  703. Vector2.prototype.subtract = function (otherVector) {
  704. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  705. };
  706. /**
  707. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  708. * Returns the Vector2.
  709. */
  710. Vector2.prototype.subtractToRef = function (otherVector, result) {
  711. result.x = this.x - otherVector.x;
  712. result.y = this.y - otherVector.y;
  713. return this;
  714. };
  715. /**
  716. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  717. * Returns the updated Vector2.
  718. */
  719. Vector2.prototype.subtractInPlace = function (otherVector) {
  720. this.x -= otherVector.x;
  721. this.y -= otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Multiplies in place the current Vector2 coordinates by the passed ones.
  726. * Returns the updated Vector2.
  727. */
  728. Vector2.prototype.multiplyInPlace = function (otherVector) {
  729. this.x *= otherVector.x;
  730. this.y *= otherVector.y;
  731. return this;
  732. };
  733. /**
  734. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  735. */
  736. Vector2.prototype.multiply = function (otherVector) {
  737. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  738. };
  739. /**
  740. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  741. * Returns the Vector2.
  742. */
  743. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  744. result.x = this.x * otherVector.x;
  745. result.y = this.y * otherVector.y;
  746. return this;
  747. };
  748. /**
  749. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  750. */
  751. Vector2.prototype.multiplyByFloats = function (x, y) {
  752. return new Vector2(this.x * x, this.y * y);
  753. };
  754. /**
  755. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  756. */
  757. Vector2.prototype.divide = function (otherVector) {
  758. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  759. };
  760. /**
  761. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  762. * Returns the Vector2.
  763. */
  764. Vector2.prototype.divideToRef = function (otherVector, result) {
  765. result.x = this.x / otherVector.x;
  766. result.y = this.y / otherVector.y;
  767. return this;
  768. };
  769. /**
  770. * Returns a new Vector2 with current Vector2 negated coordinates.
  771. */
  772. Vector2.prototype.negate = function () {
  773. return new Vector2(-this.x, -this.y);
  774. };
  775. /**
  776. * Multiply the Vector2 coordinates by scale.
  777. * Returns the updated Vector2.
  778. */
  779. Vector2.prototype.scaleInPlace = function (scale) {
  780. this.x *= scale;
  781. this.y *= scale;
  782. return this;
  783. };
  784. /**
  785. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  786. */
  787. Vector2.prototype.scale = function (scale) {
  788. return new Vector2(this.x * scale, this.y * scale);
  789. };
  790. /**
  791. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  792. */
  793. Vector2.prototype.equals = function (otherVector) {
  794. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  795. };
  796. /**
  797. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  798. */
  799. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  800. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  801. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  802. };
  803. // Properties
  804. /**
  805. * Returns the vector length (float).
  806. */
  807. Vector2.prototype.length = function () {
  808. return Math.sqrt(this.x * this.x + this.y * this.y);
  809. };
  810. /**
  811. * Returns the vector squared length (float);
  812. */
  813. Vector2.prototype.lengthSquared = function () {
  814. return (this.x * this.x + this.y * this.y);
  815. };
  816. // Methods
  817. /**
  818. * Normalize the vector.
  819. * Returns the updated Vector2.
  820. */
  821. Vector2.prototype.normalize = function () {
  822. var len = this.length();
  823. if (len === 0)
  824. return this;
  825. var num = 1.0 / len;
  826. this.x *= num;
  827. this.y *= num;
  828. return this;
  829. };
  830. /**
  831. * Returns a new Vector2 copied from the Vector2.
  832. */
  833. Vector2.prototype.clone = function () {
  834. return new Vector2(this.x, this.y);
  835. };
  836. // Statics
  837. /**
  838. * Returns a new Vector2(0, 0)
  839. */
  840. Vector2.Zero = function () {
  841. return new Vector2(0, 0);
  842. };
  843. /**
  844. * Returns a new Vector2(1, 1)
  845. */
  846. Vector2.One = function () {
  847. return new Vector2(1, 1);
  848. };
  849. /**
  850. * Returns a new Vector2 set from the passed index element of the passed array.
  851. */
  852. Vector2.FromArray = function (array, offset) {
  853. if (offset === void 0) { offset = 0; }
  854. return new Vector2(array[offset], array[offset + 1]);
  855. };
  856. /**
  857. * Sets "result" from the passed index element of the passed array.
  858. */
  859. Vector2.FromArrayToRef = function (array, offset, result) {
  860. result.x = array[offset];
  861. result.y = array[offset + 1];
  862. };
  863. /**
  864. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  865. */
  866. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  867. var squared = amount * amount;
  868. var cubed = amount * squared;
  869. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  870. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  871. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  872. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  873. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  874. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  875. return new Vector2(x, y);
  876. };
  877. /**
  878. * 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".
  879. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  880. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  881. */
  882. Vector2.Clamp = function (value, min, max) {
  883. var x = value.x;
  884. x = (x > max.x) ? max.x : x;
  885. x = (x < min.x) ? min.x : x;
  886. var y = value.y;
  887. y = (y > max.y) ? max.y : y;
  888. y = (y < min.y) ? min.y : y;
  889. return new Vector2(x, y);
  890. };
  891. /**
  892. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  893. */
  894. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  895. var squared = amount * amount;
  896. var cubed = amount * squared;
  897. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  898. var part2 = (-2.0 * cubed) + (3.0 * squared);
  899. var part3 = (cubed - (2.0 * squared)) + amount;
  900. var part4 = cubed - squared;
  901. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  902. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  903. return new Vector2(x, y);
  904. };
  905. /**
  906. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  907. */
  908. Vector2.Lerp = function (start, end, amount) {
  909. var x = start.x + ((end.x - start.x) * amount);
  910. var y = start.y + ((end.y - start.y) * amount);
  911. return new Vector2(x, y);
  912. };
  913. /**
  914. * Returns the dot product (float) of the vector "left" and the vector "right".
  915. */
  916. Vector2.Dot = function (left, right) {
  917. return left.x * right.x + left.y * right.y;
  918. };
  919. /**
  920. * Returns a new Vector2 equal to the normalized passed vector.
  921. */
  922. Vector2.Normalize = function (vector) {
  923. var newVector = vector.clone();
  924. newVector.normalize();
  925. return newVector;
  926. };
  927. /**
  928. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  929. */
  930. Vector2.Minimize = function (left, right) {
  931. var x = (left.x < right.x) ? left.x : right.x;
  932. var y = (left.y < right.y) ? left.y : right.y;
  933. return new Vector2(x, y);
  934. };
  935. /**
  936. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  937. */
  938. Vector2.Maximize = function (left, right) {
  939. var x = (left.x > right.x) ? left.x : right.x;
  940. var y = (left.y > right.y) ? left.y : right.y;
  941. return new Vector2(x, y);
  942. };
  943. /**
  944. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  945. */
  946. Vector2.Transform = function (vector, transformation) {
  947. var r = Vector2.Zero();
  948. Vector2.TransformToRef(vector, transformation, r);
  949. return r;
  950. };
  951. /**
  952. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  953. */
  954. Vector2.TransformToRef = function (vector, transformation, result) {
  955. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  956. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  957. result.x = x;
  958. result.y = y;
  959. };
  960. /**
  961. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  962. */
  963. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  964. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  965. var sign = a < 0 ? -1 : 1;
  966. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  967. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  968. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  969. };
  970. /**
  971. * Returns the distance (float) between the vectors "value1" and "value2".
  972. */
  973. Vector2.Distance = function (value1, value2) {
  974. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  975. };
  976. /**
  977. * Returns the squared distance (float) between the vectors "value1" and "value2".
  978. */
  979. Vector2.DistanceSquared = function (value1, value2) {
  980. var x = value1.x - value2.x;
  981. var y = value1.y - value2.y;
  982. return (x * x) + (y * y);
  983. };
  984. /**
  985. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  986. */
  987. Vector2.Center = function (value1, value2) {
  988. var center = value1.add(value2);
  989. center.scaleInPlace(0.5);
  990. return center;
  991. };
  992. /**
  993. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  994. */
  995. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  996. var l2 = Vector2.DistanceSquared(segA, segB);
  997. if (l2 === 0.0) {
  998. return Vector2.Distance(p, segA);
  999. }
  1000. var v = segB.subtract(segA);
  1001. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1002. var proj = segA.add(v.multiplyByFloats(t, t));
  1003. return Vector2.Distance(p, proj);
  1004. };
  1005. return Vector2;
  1006. }());
  1007. BABYLON.Vector2 = Vector2;
  1008. var Vector3 = (function () {
  1009. /**
  1010. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1011. * A Vector3 is the main object used in 3D geometry.
  1012. * It can represent etiher the coordinates of a point the space, either a direction.
  1013. */
  1014. function Vector3(x, y, z) {
  1015. this.x = x;
  1016. this.y = y;
  1017. this.z = z;
  1018. }
  1019. /**
  1020. * Returns a string with the Vector3 coordinates.
  1021. */
  1022. Vector3.prototype.toString = function () {
  1023. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1024. };
  1025. /**
  1026. * Returns the string "Vector3"
  1027. */
  1028. Vector3.prototype.getClassName = function () {
  1029. return "Vector3";
  1030. };
  1031. /**
  1032. * Returns the Vector hash code.
  1033. */
  1034. Vector3.prototype.getHashCode = function () {
  1035. var hash = this.x || 0;
  1036. hash = (hash * 397) ^ (this.y || 0);
  1037. hash = (hash * 397) ^ (this.z || 0);
  1038. return hash;
  1039. };
  1040. // Operators
  1041. /**
  1042. * Returns a new array with three elements : the coordinates the Vector3.
  1043. */
  1044. Vector3.prototype.asArray = function () {
  1045. var result = [];
  1046. this.toArray(result, 0);
  1047. return result;
  1048. };
  1049. /**
  1050. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1051. * Returns the Vector3.
  1052. */
  1053. Vector3.prototype.toArray = function (array, index) {
  1054. if (index === void 0) { index = 0; }
  1055. array[index] = this.x;
  1056. array[index + 1] = this.y;
  1057. array[index + 2] = this.z;
  1058. return this;
  1059. };
  1060. /**
  1061. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1062. */
  1063. Vector3.prototype.toQuaternion = function () {
  1064. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1065. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1066. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1067. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1068. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1069. var cosy = Math.cos(this.y * 0.5);
  1070. var siny = Math.sin(this.y * 0.5);
  1071. result.x = coszMinusx * siny;
  1072. result.y = -sinzMinusx * siny;
  1073. result.z = sinxPlusz * cosy;
  1074. result.w = cosxPlusz * cosy;
  1075. return result;
  1076. };
  1077. /**
  1078. * Adds the passed vector to the current Vector3.
  1079. * Returns the updated Vector3.
  1080. */
  1081. Vector3.prototype.addInPlace = function (otherVector) {
  1082. this.x += otherVector.x;
  1083. this.y += otherVector.y;
  1084. this.z += otherVector.z;
  1085. return this;
  1086. };
  1087. /**
  1088. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1089. */
  1090. Vector3.prototype.add = function (otherVector) {
  1091. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1092. };
  1093. /**
  1094. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1095. * Returns the current Vector3.
  1096. */
  1097. Vector3.prototype.addToRef = function (otherVector, result) {
  1098. result.x = this.x + otherVector.x;
  1099. result.y = this.y + otherVector.y;
  1100. result.z = this.z + otherVector.z;
  1101. return this;
  1102. };
  1103. /**
  1104. * Subtract the passed vector from the current Vector3.
  1105. * Returns the updated Vector3.
  1106. */
  1107. Vector3.prototype.subtractInPlace = function (otherVector) {
  1108. this.x -= otherVector.x;
  1109. this.y -= otherVector.y;
  1110. this.z -= otherVector.z;
  1111. return this;
  1112. };
  1113. /**
  1114. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1115. */
  1116. Vector3.prototype.subtract = function (otherVector) {
  1117. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1118. };
  1119. /**
  1120. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1121. * Returns the current Vector3.
  1122. */
  1123. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1124. result.x = this.x - otherVector.x;
  1125. result.y = this.y - otherVector.y;
  1126. result.z = this.z - otherVector.z;
  1127. return this;
  1128. };
  1129. /**
  1130. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1131. */
  1132. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1133. return new Vector3(this.x - x, this.y - y, this.z - z);
  1134. };
  1135. /**
  1136. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1137. * Returns the current Vector3.
  1138. */
  1139. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1140. result.x = this.x - x;
  1141. result.y = this.y - y;
  1142. result.z = this.z - z;
  1143. return this;
  1144. };
  1145. /**
  1146. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1147. */
  1148. Vector3.prototype.negate = function () {
  1149. return new Vector3(-this.x, -this.y, -this.z);
  1150. };
  1151. /**
  1152. * Multiplies the Vector3 coordinates by the float "scale".
  1153. * Returns the updated Vector3.
  1154. */
  1155. Vector3.prototype.scaleInPlace = function (scale) {
  1156. this.x *= scale;
  1157. this.y *= scale;
  1158. this.z *= scale;
  1159. return this;
  1160. };
  1161. /**
  1162. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1163. */
  1164. Vector3.prototype.scale = function (scale) {
  1165. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1166. };
  1167. /**
  1168. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1169. * Returns the current Vector3.
  1170. */
  1171. Vector3.prototype.scaleToRef = function (scale, result) {
  1172. result.x = this.x * scale;
  1173. result.y = this.y * scale;
  1174. result.z = this.z * scale;
  1175. return this;
  1176. };
  1177. /**
  1178. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1179. */
  1180. Vector3.prototype.equals = function (otherVector) {
  1181. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1182. };
  1183. /**
  1184. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1185. */
  1186. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1187. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1188. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1189. };
  1190. /**
  1191. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1192. */
  1193. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1194. return this.x === x && this.y === y && this.z === z;
  1195. };
  1196. /**
  1197. * Muliplies the current Vector3 coordinates by the passed ones.
  1198. * Returns the updated Vector3.
  1199. */
  1200. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1201. this.x *= otherVector.x;
  1202. this.y *= otherVector.y;
  1203. this.z *= otherVector.z;
  1204. return this;
  1205. };
  1206. /**
  1207. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1208. */
  1209. Vector3.prototype.multiply = function (otherVector) {
  1210. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1211. };
  1212. /**
  1213. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1214. * Returns the current Vector3.
  1215. */
  1216. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1217. result.x = this.x * otherVector.x;
  1218. result.y = this.y * otherVector.y;
  1219. result.z = this.z * otherVector.z;
  1220. return this;
  1221. };
  1222. /**
  1223. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1224. */
  1225. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1226. return new Vector3(this.x * x, this.y * y, this.z * z);
  1227. };
  1228. /**
  1229. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1230. */
  1231. Vector3.prototype.divide = function (otherVector) {
  1232. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1233. };
  1234. /**
  1235. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1236. * Returns the current Vector3.
  1237. */
  1238. Vector3.prototype.divideToRef = function (otherVector, result) {
  1239. result.x = this.x / otherVector.x;
  1240. result.y = this.y / otherVector.y;
  1241. result.z = this.z / otherVector.z;
  1242. return this;
  1243. };
  1244. /**
  1245. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1246. * Returns the updated Vector3.
  1247. */
  1248. Vector3.prototype.MinimizeInPlace = function (other) {
  1249. if (other.x < this.x)
  1250. this.x = other.x;
  1251. if (other.y < this.y)
  1252. this.y = other.y;
  1253. if (other.z < this.z)
  1254. this.z = other.z;
  1255. return this;
  1256. };
  1257. /**
  1258. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1259. * Returns the updated Vector3.
  1260. */
  1261. Vector3.prototype.MaximizeInPlace = function (other) {
  1262. if (other.x > this.x)
  1263. this.x = other.x;
  1264. if (other.y > this.y)
  1265. this.y = other.y;
  1266. if (other.z > this.z)
  1267. this.z = other.z;
  1268. return this;
  1269. };
  1270. // Properties
  1271. /**
  1272. * Returns the length of the Vector3 (float).
  1273. */
  1274. Vector3.prototype.length = function () {
  1275. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1276. };
  1277. /**
  1278. * Returns the squared length of the Vector3 (float).
  1279. */
  1280. Vector3.prototype.lengthSquared = function () {
  1281. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1282. };
  1283. // Methods
  1284. /**
  1285. * Normalize the current Vector3.
  1286. * Returns the updated Vector3.
  1287. */
  1288. Vector3.prototype.normalize = function () {
  1289. var len = this.length();
  1290. if (len === 0 || len === 1.0)
  1291. return this;
  1292. var num = 1.0 / len;
  1293. this.x *= num;
  1294. this.y *= num;
  1295. this.z *= num;
  1296. return this;
  1297. };
  1298. /**
  1299. * Returns a new Vector3 copied from the current Vector3.
  1300. */
  1301. Vector3.prototype.clone = function () {
  1302. return new Vector3(this.x, this.y, this.z);
  1303. };
  1304. /**
  1305. * Copies the passed vector coordinates to the current Vector3 ones.
  1306. * Returns the updated Vector3.
  1307. */
  1308. Vector3.prototype.copyFrom = function (source) {
  1309. this.x = source.x;
  1310. this.y = source.y;
  1311. this.z = source.z;
  1312. return this;
  1313. };
  1314. /**
  1315. * Copies the passed floats to the current Vector3 coordinates.
  1316. * Returns the updated Vector3.
  1317. */
  1318. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1319. this.x = x;
  1320. this.y = y;
  1321. this.z = z;
  1322. return this;
  1323. };
  1324. /**
  1325. * Copies the passed floats to the current Vector3 coordinates.
  1326. * Returns the updated Vector3.
  1327. */
  1328. Vector3.prototype.set = function (x, y, z) {
  1329. return this.copyFromFloats(x, y, z);
  1330. };
  1331. // Statics
  1332. /**
  1333. *
  1334. */
  1335. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1336. var d0 = Vector3.Dot(vector0, axis) - size;
  1337. var d1 = Vector3.Dot(vector1, axis) - size;
  1338. var s = d0 / (d0 - d1);
  1339. return s;
  1340. };
  1341. /**
  1342. * Returns a new Vector3 set from the index "offset" of the passed array.
  1343. */
  1344. Vector3.FromArray = function (array, offset) {
  1345. if (!offset) {
  1346. offset = 0;
  1347. }
  1348. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1349. };
  1350. /**
  1351. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1352. * This function is deprecated. Use FromArray instead.
  1353. */
  1354. Vector3.FromFloatArray = function (array, offset) {
  1355. return Vector3.FromArray(array, offset);
  1356. };
  1357. /**
  1358. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1359. */
  1360. Vector3.FromArrayToRef = function (array, offset, result) {
  1361. result.x = array[offset];
  1362. result.y = array[offset + 1];
  1363. result.z = array[offset + 2];
  1364. };
  1365. /**
  1366. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1367. * This function is deprecated. Use FromArrayToRef instead.
  1368. */
  1369. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1370. return Vector3.FromArrayToRef(array, offset, result);
  1371. };
  1372. /**
  1373. * Sets the passed vector "result" with the passed floats.
  1374. */
  1375. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1376. result.x = x;
  1377. result.y = y;
  1378. result.z = z;
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1382. */
  1383. Vector3.Zero = function () {
  1384. return new Vector3(0.0, 0.0, 0.0);
  1385. };
  1386. /**
  1387. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1388. */
  1389. Vector3.One = function () {
  1390. return new Vector3(1.0, 1.0, 1.0);
  1391. };
  1392. /**
  1393. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1394. */
  1395. Vector3.Up = function () {
  1396. return new Vector3(0.0, 1.0, 0.0);
  1397. };
  1398. /**
  1399. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1400. */
  1401. Vector3.Forward = function () {
  1402. return new Vector3(0.0, 0.0, 1.0);
  1403. };
  1404. /**
  1405. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1406. */
  1407. Vector3.Right = function () {
  1408. return new Vector3(1.0, 0.0, 0.0);
  1409. };
  1410. /**
  1411. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1412. */
  1413. Vector3.Left = function () {
  1414. return new Vector3(-1.0, 0.0, 0.0);
  1415. };
  1416. /**
  1417. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1418. * This method computes tranformed coordinates only, not transformed direction vectors.
  1419. */
  1420. Vector3.TransformCoordinates = function (vector, transformation) {
  1421. var result = Vector3.Zero();
  1422. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1423. return result;
  1424. };
  1425. /**
  1426. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1427. * This method computes tranformed coordinates only, not transformed direction vectors.
  1428. */
  1429. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1430. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1431. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1432. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1433. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1434. result.x = x / w;
  1435. result.y = y / w;
  1436. result.z = z / w;
  1437. };
  1438. /**
  1439. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1440. * This method computes tranformed coordinates only, not transformed direction vectors.
  1441. */
  1442. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1443. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1444. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1445. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1446. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1447. result.x = rx / rw;
  1448. result.y = ry / rw;
  1449. result.z = rz / rw;
  1450. };
  1451. /**
  1452. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1453. * This methods computes transformed normalized direction vectors only.
  1454. */
  1455. Vector3.TransformNormal = function (vector, transformation) {
  1456. var result = Vector3.Zero();
  1457. Vector3.TransformNormalToRef(vector, transformation, result);
  1458. return result;
  1459. };
  1460. /**
  1461. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1462. * This methods computes transformed normalized direction vectors only.
  1463. */
  1464. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1465. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1466. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1467. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1468. result.x = x;
  1469. result.y = y;
  1470. result.z = z;
  1471. };
  1472. /**
  1473. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1474. * This methods computes transformed normalized direction vectors only.
  1475. */
  1476. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1477. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1478. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1479. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1480. };
  1481. /**
  1482. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1483. */
  1484. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1485. var squared = amount * amount;
  1486. var cubed = amount * squared;
  1487. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1488. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1489. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1490. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1491. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1492. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1493. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1494. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1495. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1496. return new Vector3(x, y, z);
  1497. };
  1498. /**
  1499. * 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".
  1500. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1501. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1502. */
  1503. Vector3.Clamp = function (value, min, max) {
  1504. var x = value.x;
  1505. x = (x > max.x) ? max.x : x;
  1506. x = (x < min.x) ? min.x : x;
  1507. var y = value.y;
  1508. y = (y > max.y) ? max.y : y;
  1509. y = (y < min.y) ? min.y : y;
  1510. var z = value.z;
  1511. z = (z > max.z) ? max.z : z;
  1512. z = (z < min.z) ? min.z : z;
  1513. return new Vector3(x, y, z);
  1514. };
  1515. /**
  1516. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1517. */
  1518. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1519. var squared = amount * amount;
  1520. var cubed = amount * squared;
  1521. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1522. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1523. var part3 = (cubed - (2.0 * squared)) + amount;
  1524. var part4 = cubed - squared;
  1525. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1526. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1527. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1528. return new Vector3(x, y, z);
  1529. };
  1530. /**
  1531. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1532. */
  1533. Vector3.Lerp = function (start, end, amount) {
  1534. var result = new Vector3(0, 0, 0);
  1535. Vector3.LerpToRef(start, end, amount, result);
  1536. return result;
  1537. };
  1538. /**
  1539. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1540. */
  1541. Vector3.LerpToRef = function (start, end, amount, result) {
  1542. result.x = start.x + ((end.x - start.x) * amount);
  1543. result.y = start.y + ((end.y - start.y) * amount);
  1544. result.z = start.z + ((end.z - start.z) * amount);
  1545. };
  1546. /**
  1547. * Returns the dot product (float) between the vectors "left" and "right".
  1548. */
  1549. Vector3.Dot = function (left, right) {
  1550. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1551. };
  1552. /**
  1553. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1554. * The cross product is then orthogonal to both "left" and "right".
  1555. */
  1556. Vector3.Cross = function (left, right) {
  1557. var result = Vector3.Zero();
  1558. Vector3.CrossToRef(left, right, result);
  1559. return result;
  1560. };
  1561. /**
  1562. * Sets the passed vector "result" with the cross product of "left" and "right".
  1563. * The cross product is then orthogonal to both "left" and "right".
  1564. */
  1565. Vector3.CrossToRef = function (left, right, result) {
  1566. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1567. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1568. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1569. result.copyFrom(MathTmp.Vector3[0]);
  1570. };
  1571. /**
  1572. * Returns a new Vector3 as the normalization of the passed vector.
  1573. */
  1574. Vector3.Normalize = function (vector) {
  1575. var result = Vector3.Zero();
  1576. Vector3.NormalizeToRef(vector, result);
  1577. return result;
  1578. };
  1579. /**
  1580. * Sets the passed vector "result" with the normalization of the passed first vector.
  1581. */
  1582. Vector3.NormalizeToRef = function (vector, result) {
  1583. result.copyFrom(vector);
  1584. result.normalize();
  1585. };
  1586. Vector3.Project = function (vector, world, transform, viewport) {
  1587. var cw = viewport.width;
  1588. var ch = viewport.height;
  1589. var cx = viewport.x;
  1590. var cy = viewport.y;
  1591. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1592. 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);
  1593. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1594. world.multiplyToRef(transform, matrix);
  1595. matrix.multiplyToRef(viewportMatrix, matrix);
  1596. return Vector3.TransformCoordinates(vector, matrix);
  1597. };
  1598. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1599. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1600. world.multiplyToRef(transform, matrix);
  1601. matrix.invert();
  1602. source.x = source.x / viewportWidth * 2 - 1;
  1603. source.y = -(source.y / viewportHeight * 2 - 1);
  1604. var vector = Vector3.TransformCoordinates(source, matrix);
  1605. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1606. if (MathTools.WithinEpsilon(num, 1.0)) {
  1607. vector = vector.scale(1.0 / num);
  1608. }
  1609. return vector;
  1610. };
  1611. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1612. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1613. world.multiplyToRef(view, matrix);
  1614. matrix.multiplyToRef(projection, matrix);
  1615. matrix.invert();
  1616. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1617. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1618. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1619. if (MathTools.WithinEpsilon(num, 1.0)) {
  1620. vector = vector.scale(1.0 / num);
  1621. }
  1622. return vector;
  1623. };
  1624. Vector3.Minimize = function (left, right) {
  1625. var min = left.clone();
  1626. min.MinimizeInPlace(right);
  1627. return min;
  1628. };
  1629. Vector3.Maximize = function (left, right) {
  1630. var max = left.clone();
  1631. max.MaximizeInPlace(right);
  1632. return max;
  1633. };
  1634. /**
  1635. * Returns the distance (float) between the vectors "value1" and "value2".
  1636. */
  1637. Vector3.Distance = function (value1, value2) {
  1638. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1639. };
  1640. /**
  1641. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1642. */
  1643. Vector3.DistanceSquared = function (value1, value2) {
  1644. var x = value1.x - value2.x;
  1645. var y = value1.y - value2.y;
  1646. var z = value1.z - value2.z;
  1647. return (x * x) + (y * y) + (z * z);
  1648. };
  1649. /**
  1650. * Returns a new Vector3 located at the center between "value1" and "value2".
  1651. */
  1652. Vector3.Center = function (value1, value2) {
  1653. var center = value1.add(value2);
  1654. center.scaleInPlace(0.5);
  1655. return center;
  1656. };
  1657. /**
  1658. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1659. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1660. * to something in order to rotate it from its local system to the given target system.
  1661. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1662. * Returns a new Vector3.
  1663. */
  1664. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1665. var rotation = Vector3.Zero();
  1666. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1667. return rotation;
  1668. };
  1669. /**
  1670. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1671. */
  1672. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1673. var quat = MathTmp.Quaternion[0];
  1674. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1675. quat.toEulerAnglesToRef(ref);
  1676. };
  1677. return Vector3;
  1678. }());
  1679. BABYLON.Vector3 = Vector3;
  1680. //Vector4 class created for EulerAngle class conversion to Quaternion
  1681. var Vector4 = (function () {
  1682. /**
  1683. * Creates a Vector4 object from the passed floats.
  1684. */
  1685. function Vector4(x, y, z, w) {
  1686. this.x = x;
  1687. this.y = y;
  1688. this.z = z;
  1689. this.w = w;
  1690. }
  1691. /**
  1692. * Returns the string with the Vector4 coordinates.
  1693. */
  1694. Vector4.prototype.toString = function () {
  1695. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1696. };
  1697. /**
  1698. * Returns the string "Vector4".
  1699. */
  1700. Vector4.prototype.getClassName = function () {
  1701. return "Vector4";
  1702. };
  1703. /**
  1704. * Returns the Vector4 hash code.
  1705. */
  1706. Vector4.prototype.getHashCode = function () {
  1707. var hash = this.x || 0;
  1708. hash = (hash * 397) ^ (this.y || 0);
  1709. hash = (hash * 397) ^ (this.z || 0);
  1710. hash = (hash * 397) ^ (this.w || 0);
  1711. return hash;
  1712. };
  1713. // Operators
  1714. /**
  1715. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1716. */
  1717. Vector4.prototype.asArray = function () {
  1718. var result = [];
  1719. this.toArray(result, 0);
  1720. return result;
  1721. };
  1722. /**
  1723. * Populates the passed array from the passed index with the Vector4 coordinates.
  1724. * Returns the Vector4.
  1725. */
  1726. Vector4.prototype.toArray = function (array, index) {
  1727. if (index === undefined) {
  1728. index = 0;
  1729. }
  1730. array[index] = this.x;
  1731. array[index + 1] = this.y;
  1732. array[index + 2] = this.z;
  1733. array[index + 3] = this.w;
  1734. return this;
  1735. };
  1736. /**
  1737. * Adds the passed vector to the current Vector4.
  1738. * Returns the updated Vector4.
  1739. */
  1740. Vector4.prototype.addInPlace = function (otherVector) {
  1741. this.x += otherVector.x;
  1742. this.y += otherVector.y;
  1743. this.z += otherVector.z;
  1744. this.w += otherVector.w;
  1745. return this;
  1746. };
  1747. /**
  1748. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1749. */
  1750. Vector4.prototype.add = function (otherVector) {
  1751. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1752. };
  1753. /**
  1754. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1755. * Returns the current Vector4.
  1756. */
  1757. Vector4.prototype.addToRef = function (otherVector, result) {
  1758. result.x = this.x + otherVector.x;
  1759. result.y = this.y + otherVector.y;
  1760. result.z = this.z + otherVector.z;
  1761. result.w = this.w + otherVector.w;
  1762. return this;
  1763. };
  1764. /**
  1765. * Subtract in place the passed vector from the current Vector4.
  1766. * Returns the updated Vector4.
  1767. */
  1768. Vector4.prototype.subtractInPlace = function (otherVector) {
  1769. this.x -= otherVector.x;
  1770. this.y -= otherVector.y;
  1771. this.z -= otherVector.z;
  1772. this.w -= otherVector.w;
  1773. return this;
  1774. };
  1775. /**
  1776. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1777. */
  1778. Vector4.prototype.subtract = function (otherVector) {
  1779. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1780. };
  1781. /**
  1782. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1783. * Returns the current Vector4.
  1784. */
  1785. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1786. result.x = this.x - otherVector.x;
  1787. result.y = this.y - otherVector.y;
  1788. result.z = this.z - otherVector.z;
  1789. result.w = this.w - otherVector.w;
  1790. return this;
  1791. };
  1792. /**
  1793. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1794. */
  1795. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1796. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1797. };
  1798. /**
  1799. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1800. * Returns the current Vector4.
  1801. */
  1802. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1803. result.x = this.x - x;
  1804. result.y = this.y - y;
  1805. result.z = this.z - z;
  1806. result.w = this.w - w;
  1807. return this;
  1808. };
  1809. /**
  1810. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1811. */
  1812. Vector4.prototype.negate = function () {
  1813. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1814. };
  1815. /**
  1816. * Multiplies the current Vector4 coordinates by scale (float).
  1817. * Returns the updated Vector4.
  1818. */
  1819. Vector4.prototype.scaleInPlace = function (scale) {
  1820. this.x *= scale;
  1821. this.y *= scale;
  1822. this.z *= scale;
  1823. this.w *= scale;
  1824. return this;
  1825. };
  1826. /**
  1827. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1828. */
  1829. Vector4.prototype.scale = function (scale) {
  1830. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1831. };
  1832. /**
  1833. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1834. * Returns the current Vector4.
  1835. */
  1836. Vector4.prototype.scaleToRef = function (scale, result) {
  1837. result.x = this.x * scale;
  1838. result.y = this.y * scale;
  1839. result.z = this.z * scale;
  1840. result.w = this.w * scale;
  1841. return this;
  1842. };
  1843. /**
  1844. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1845. */
  1846. Vector4.prototype.equals = function (otherVector) {
  1847. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1848. };
  1849. /**
  1850. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1851. */
  1852. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1853. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1854. return otherVector
  1855. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1856. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1857. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1858. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1859. };
  1860. /**
  1861. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1862. */
  1863. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1864. return this.x === x && this.y === y && this.z === z && this.w === w;
  1865. };
  1866. /**
  1867. * Multiplies in place the current Vector4 by the passed one.
  1868. * Returns the updated Vector4.
  1869. */
  1870. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1871. this.x *= otherVector.x;
  1872. this.y *= otherVector.y;
  1873. this.z *= otherVector.z;
  1874. this.w *= otherVector.w;
  1875. return this;
  1876. };
  1877. /**
  1878. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1879. */
  1880. Vector4.prototype.multiply = function (otherVector) {
  1881. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1882. };
  1883. /**
  1884. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1885. * Returns the current Vector4.
  1886. */
  1887. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1888. result.x = this.x * otherVector.x;
  1889. result.y = this.y * otherVector.y;
  1890. result.z = this.z * otherVector.z;
  1891. result.w = this.w * otherVector.w;
  1892. return this;
  1893. };
  1894. /**
  1895. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1896. */
  1897. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1898. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1899. };
  1900. /**
  1901. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1902. */
  1903. Vector4.prototype.divide = function (otherVector) {
  1904. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1905. };
  1906. /**
  1907. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1908. * Returns the current Vector4.
  1909. */
  1910. Vector4.prototype.divideToRef = function (otherVector, result) {
  1911. result.x = this.x / otherVector.x;
  1912. result.y = this.y / otherVector.y;
  1913. result.z = this.z / otherVector.z;
  1914. result.w = this.w / otherVector.w;
  1915. return this;
  1916. };
  1917. /**
  1918. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1919. */
  1920. Vector4.prototype.MinimizeInPlace = function (other) {
  1921. if (other.x < this.x)
  1922. this.x = other.x;
  1923. if (other.y < this.y)
  1924. this.y = other.y;
  1925. if (other.z < this.z)
  1926. this.z = other.z;
  1927. if (other.w < this.w)
  1928. this.w = other.w;
  1929. return this;
  1930. };
  1931. /**
  1932. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1933. */
  1934. Vector4.prototype.MaximizeInPlace = function (other) {
  1935. if (other.x > this.x)
  1936. this.x = other.x;
  1937. if (other.y > this.y)
  1938. this.y = other.y;
  1939. if (other.z > this.z)
  1940. this.z = other.z;
  1941. if (other.w > this.w)
  1942. this.w = other.w;
  1943. return this;
  1944. };
  1945. // Properties
  1946. /**
  1947. * Returns the Vector4 length (float).
  1948. */
  1949. Vector4.prototype.length = function () {
  1950. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1951. };
  1952. /**
  1953. * Returns the Vector4 squared length (float).
  1954. */
  1955. Vector4.prototype.lengthSquared = function () {
  1956. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1957. };
  1958. // Methods
  1959. /**
  1960. * Normalizes in place the Vector4.
  1961. * Returns the updated Vector4.
  1962. */
  1963. Vector4.prototype.normalize = function () {
  1964. var len = this.length();
  1965. if (len === 0)
  1966. return this;
  1967. var num = 1.0 / len;
  1968. this.x *= num;
  1969. this.y *= num;
  1970. this.z *= num;
  1971. this.w *= num;
  1972. return this;
  1973. };
  1974. /**
  1975. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1976. */
  1977. Vector4.prototype.toVector3 = function () {
  1978. return new Vector3(this.x, this.y, this.z);
  1979. };
  1980. /**
  1981. * Returns a new Vector4 copied from the current one.
  1982. */
  1983. Vector4.prototype.clone = function () {
  1984. return new Vector4(this.x, this.y, this.z, this.w);
  1985. };
  1986. /**
  1987. * Updates the current Vector4 with the passed one coordinates.
  1988. * Returns the updated Vector4.
  1989. */
  1990. Vector4.prototype.copyFrom = function (source) {
  1991. this.x = source.x;
  1992. this.y = source.y;
  1993. this.z = source.z;
  1994. this.w = source.w;
  1995. return this;
  1996. };
  1997. /**
  1998. * Updates the current Vector4 coordinates with the passed floats.
  1999. * Returns the updated Vector4.
  2000. */
  2001. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2002. this.x = x;
  2003. this.y = y;
  2004. this.z = z;
  2005. this.w = w;
  2006. return this;
  2007. };
  2008. /**
  2009. * Updates the current Vector4 coordinates with the passed floats.
  2010. * Returns the updated Vector4.
  2011. */
  2012. Vector4.prototype.set = function (x, y, z, w) {
  2013. return this.copyFromFloats(x, y, z, w);
  2014. };
  2015. // Statics
  2016. /**
  2017. * Returns a new Vector4 set from the starting index of the passed array.
  2018. */
  2019. Vector4.FromArray = function (array, offset) {
  2020. if (!offset) {
  2021. offset = 0;
  2022. }
  2023. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2024. };
  2025. /**
  2026. * Updates the passed vector "result" from the starting index of the passed array.
  2027. */
  2028. Vector4.FromArrayToRef = function (array, offset, result) {
  2029. result.x = array[offset];
  2030. result.y = array[offset + 1];
  2031. result.z = array[offset + 2];
  2032. result.w = array[offset + 3];
  2033. };
  2034. /**
  2035. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2036. */
  2037. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2038. Vector4.FromArrayToRef(array, offset, result);
  2039. };
  2040. /**
  2041. * Updates the passed vector "result" coordinates from the passed floats.
  2042. */
  2043. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2044. result.x = x;
  2045. result.y = y;
  2046. result.z = z;
  2047. result.w = w;
  2048. };
  2049. /**
  2050. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2051. */
  2052. Vector4.Zero = function () {
  2053. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2054. };
  2055. /**
  2056. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2057. */
  2058. Vector4.One = function () {
  2059. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2060. };
  2061. /**
  2062. * Returns a new normalized Vector4 from the passed one.
  2063. */
  2064. Vector4.Normalize = function (vector) {
  2065. var result = Vector4.Zero();
  2066. Vector4.NormalizeToRef(vector, result);
  2067. return result;
  2068. };
  2069. /**
  2070. * Updates the passed vector "result" from the normalization of the passed one.
  2071. */
  2072. Vector4.NormalizeToRef = function (vector, result) {
  2073. result.copyFrom(vector);
  2074. result.normalize();
  2075. };
  2076. Vector4.Minimize = function (left, right) {
  2077. var min = left.clone();
  2078. min.MinimizeInPlace(right);
  2079. return min;
  2080. };
  2081. Vector4.Maximize = function (left, right) {
  2082. var max = left.clone();
  2083. max.MaximizeInPlace(right);
  2084. return max;
  2085. };
  2086. /**
  2087. * Returns the distance (float) between the vectors "value1" and "value2".
  2088. */
  2089. Vector4.Distance = function (value1, value2) {
  2090. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2091. };
  2092. /**
  2093. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2094. */
  2095. Vector4.DistanceSquared = function (value1, value2) {
  2096. var x = value1.x - value2.x;
  2097. var y = value1.y - value2.y;
  2098. var z = value1.z - value2.z;
  2099. var w = value1.w - value2.w;
  2100. return (x * x) + (y * y) + (z * z) + (w * w);
  2101. };
  2102. /**
  2103. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2104. */
  2105. Vector4.Center = function (value1, value2) {
  2106. var center = value1.add(value2);
  2107. center.scaleInPlace(0.5);
  2108. return center;
  2109. };
  2110. /**
  2111. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2112. * This methods computes transformed normalized direction vectors only.
  2113. */
  2114. Vector4.TransformNormal = function (vector, transformation) {
  2115. var result = Vector4.Zero();
  2116. Vector4.TransformNormalToRef(vector, transformation, result);
  2117. return result;
  2118. };
  2119. /**
  2120. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2121. * This methods computes transformed normalized direction vectors only.
  2122. */
  2123. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2124. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2125. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2126. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2127. result.x = x;
  2128. result.y = y;
  2129. result.z = z;
  2130. result.w = vector.w;
  2131. };
  2132. /**
  2133. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2134. * This methods computes transformed normalized direction vectors only.
  2135. */
  2136. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2137. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2138. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2139. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2140. result.w = w;
  2141. };
  2142. return Vector4;
  2143. }());
  2144. BABYLON.Vector4 = Vector4;
  2145. var Size = (function () {
  2146. /**
  2147. * Creates a Size object from the passed width and height (floats).
  2148. */
  2149. function Size(width, height) {
  2150. this.width = width;
  2151. this.height = height;
  2152. }
  2153. // Returns a string with the Size width and height.
  2154. Size.prototype.toString = function () {
  2155. return "{W: " + this.width + ", H: " + this.height + "}";
  2156. };
  2157. /**
  2158. * Returns the string "Size"
  2159. */
  2160. Size.prototype.getClassName = function () {
  2161. return "Size";
  2162. };
  2163. /**
  2164. * Returns the Size hash code.
  2165. */
  2166. Size.prototype.getHashCode = function () {
  2167. var hash = this.width || 0;
  2168. hash = (hash * 397) ^ (this.height || 0);
  2169. return hash;
  2170. };
  2171. /**
  2172. * Updates the current size from the passed one.
  2173. * Returns the updated Size.
  2174. */
  2175. Size.prototype.copyFrom = function (src) {
  2176. this.width = src.width;
  2177. this.height = src.height;
  2178. };
  2179. /**
  2180. * Updates in place the current Size from the passed floats.
  2181. * Returns the updated Size.
  2182. */
  2183. Size.prototype.copyFromFloats = function (width, height) {
  2184. this.width = width;
  2185. this.height = height;
  2186. return this;
  2187. };
  2188. /**
  2189. * Updates in place the current Size from the passed floats.
  2190. * Returns the updated Size.
  2191. */
  2192. Size.prototype.set = function (width, height) {
  2193. return this.copyFromFloats(width, height);
  2194. };
  2195. /**
  2196. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2197. */
  2198. Size.prototype.multiplyByFloats = function (w, h) {
  2199. return new Size(this.width * w, this.height * h);
  2200. };
  2201. /**
  2202. * Returns a new Size copied from the passed one.
  2203. */
  2204. Size.prototype.clone = function () {
  2205. return new Size(this.width, this.height);
  2206. };
  2207. /**
  2208. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2209. */
  2210. Size.prototype.equals = function (other) {
  2211. if (!other) {
  2212. return false;
  2213. }
  2214. return (this.width === other.width) && (this.height === other.height);
  2215. };
  2216. Object.defineProperty(Size.prototype, "surface", {
  2217. /**
  2218. * Returns the surface of the Size : width * height (float).
  2219. */
  2220. get: function () {
  2221. return this.width * this.height;
  2222. },
  2223. enumerable: true,
  2224. configurable: true
  2225. });
  2226. /**
  2227. * Returns a new Size set to (0.0, 0.0)
  2228. */
  2229. Size.Zero = function () {
  2230. return new Size(0.0, 0.0);
  2231. };
  2232. /**
  2233. * Returns a new Size set as the addition result of the current Size and the passed one.
  2234. */
  2235. Size.prototype.add = function (otherSize) {
  2236. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2237. return r;
  2238. };
  2239. /**
  2240. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2241. */
  2242. Size.prototype.subtract = function (otherSize) {
  2243. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2244. return r;
  2245. };
  2246. /**
  2247. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2248. */
  2249. Size.Lerp = function (start, end, amount) {
  2250. var w = start.width + ((end.width - start.width) * amount);
  2251. var h = start.height + ((end.height - start.height) * amount);
  2252. return new Size(w, h);
  2253. };
  2254. return Size;
  2255. }());
  2256. BABYLON.Size = Size;
  2257. var Quaternion = (function () {
  2258. /**
  2259. * Creates a new Quaternion from the passed floats.
  2260. */
  2261. function Quaternion(x, y, z, w) {
  2262. if (x === void 0) { x = 0.0; }
  2263. if (y === void 0) { y = 0.0; }
  2264. if (z === void 0) { z = 0.0; }
  2265. if (w === void 0) { w = 1.0; }
  2266. this.x = x;
  2267. this.y = y;
  2268. this.z = z;
  2269. this.w = w;
  2270. }
  2271. /**
  2272. * Returns a string with the Quaternion coordinates.
  2273. */
  2274. Quaternion.prototype.toString = function () {
  2275. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2276. };
  2277. /**
  2278. * Returns the string "Quaternion".
  2279. */
  2280. Quaternion.prototype.getClassName = function () {
  2281. return "Quaternion";
  2282. };
  2283. /**
  2284. * Returns the Quaternion hash code.
  2285. */
  2286. Quaternion.prototype.getHashCode = function () {
  2287. var hash = this.x || 0;
  2288. hash = (hash * 397) ^ (this.y || 0);
  2289. hash = (hash * 397) ^ (this.z || 0);
  2290. hash = (hash * 397) ^ (this.w || 0);
  2291. return hash;
  2292. };
  2293. /**
  2294. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2295. */
  2296. Quaternion.prototype.asArray = function () {
  2297. return [this.x, this.y, this.z, this.w];
  2298. };
  2299. /**
  2300. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2301. */
  2302. Quaternion.prototype.equals = function (otherQuaternion) {
  2303. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2304. };
  2305. /**
  2306. * Returns a new Quaternion copied from the current one.
  2307. */
  2308. Quaternion.prototype.clone = function () {
  2309. return new Quaternion(this.x, this.y, this.z, this.w);
  2310. };
  2311. /**
  2312. * Updates the current Quaternion from the passed one coordinates.
  2313. * Returns the updated Quaterion.
  2314. */
  2315. Quaternion.prototype.copyFrom = function (other) {
  2316. this.x = other.x;
  2317. this.y = other.y;
  2318. this.z = other.z;
  2319. this.w = other.w;
  2320. return this;
  2321. };
  2322. /**
  2323. * Updates the current Quaternion from the passed float coordinates.
  2324. * Returns the updated Quaterion.
  2325. */
  2326. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2327. this.x = x;
  2328. this.y = y;
  2329. this.z = z;
  2330. this.w = w;
  2331. return this;
  2332. };
  2333. /**
  2334. * Updates the current Quaternion from the passed float coordinates.
  2335. * Returns the updated Quaterion.
  2336. */
  2337. Quaternion.prototype.set = function (x, y, z, w) {
  2338. return this.copyFromFloats(x, y, z, w);
  2339. };
  2340. /**
  2341. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2342. */
  2343. Quaternion.prototype.add = function (other) {
  2344. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2345. };
  2346. /**
  2347. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2348. */
  2349. Quaternion.prototype.subtract = function (other) {
  2350. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2351. };
  2352. /**
  2353. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2354. */
  2355. Quaternion.prototype.scale = function (value) {
  2356. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2357. };
  2358. /**
  2359. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2360. */
  2361. Quaternion.prototype.multiply = function (q1) {
  2362. var result = new Quaternion(0, 0, 0, 1.0);
  2363. this.multiplyToRef(q1, result);
  2364. return result;
  2365. };
  2366. /**
  2367. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2368. * Returns the current Quaternion.
  2369. */
  2370. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2371. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2372. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2373. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2374. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2375. result.copyFromFloats(x, y, z, w);
  2376. return this;
  2377. };
  2378. /**
  2379. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2380. * Returns the updated Quaternion.
  2381. */
  2382. Quaternion.prototype.multiplyInPlace = function (q1) {
  2383. this.multiplyToRef(q1, this);
  2384. return this;
  2385. };
  2386. /**
  2387. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2388. * Returns the current Quaternion.
  2389. */
  2390. Quaternion.prototype.conjugateToRef = function (ref) {
  2391. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2392. return this;
  2393. };
  2394. /**
  2395. * Conjugates in place the current Quaternion.
  2396. * Returns the updated Quaternion.
  2397. */
  2398. Quaternion.prototype.conjugateInPlace = function () {
  2399. this.x *= -1;
  2400. this.y *= -1;
  2401. this.z *= -1;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2406. */
  2407. Quaternion.prototype.conjugate = function () {
  2408. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2409. return result;
  2410. };
  2411. /**
  2412. * Returns the Quaternion length (float).
  2413. */
  2414. Quaternion.prototype.length = function () {
  2415. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2416. };
  2417. /**
  2418. * Normalize in place the current Quaternion.
  2419. * Returns the updated Quaternion.
  2420. */
  2421. Quaternion.prototype.normalize = function () {
  2422. var length = 1.0 / this.length();
  2423. this.x *= length;
  2424. this.y *= length;
  2425. this.z *= length;
  2426. this.w *= length;
  2427. return this;
  2428. };
  2429. /**
  2430. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2431. */
  2432. Quaternion.prototype.toEulerAngles = function (order) {
  2433. if (order === void 0) { order = "YZX"; }
  2434. var result = Vector3.Zero();
  2435. this.toEulerAnglesToRef(result, order);
  2436. return result;
  2437. };
  2438. /**
  2439. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2440. * Returns the current Quaternion.
  2441. */
  2442. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2443. if (order === void 0) { order = "YZX"; }
  2444. var qz = this.z;
  2445. var qx = this.x;
  2446. var qy = this.y;
  2447. var qw = this.w;
  2448. var sqw = qw * qw;
  2449. var sqz = qz * qz;
  2450. var sqx = qx * qx;
  2451. var sqy = qy * qy;
  2452. var zAxisY = qy * qz - qx * qw;
  2453. var limit = .4999999;
  2454. if (zAxisY < -limit) {
  2455. result.y = 2 * Math.atan2(qy, qw);
  2456. result.x = Math.PI / 2;
  2457. result.z = 0;
  2458. }
  2459. else if (zAxisY > limit) {
  2460. result.y = 2 * Math.atan2(qy, qw);
  2461. result.x = -Math.PI / 2;
  2462. result.z = 0;
  2463. }
  2464. else {
  2465. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2466. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2467. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2468. }
  2469. return this;
  2470. };
  2471. /**
  2472. * Updates the passed rotation matrix with the current Quaternion values.
  2473. * Returns the current Quaternion.
  2474. */
  2475. Quaternion.prototype.toRotationMatrix = function (result) {
  2476. var xx = this.x * this.x;
  2477. var yy = this.y * this.y;
  2478. var zz = this.z * this.z;
  2479. var xy = this.x * this.y;
  2480. var zw = this.z * this.w;
  2481. var zx = this.z * this.x;
  2482. var yw = this.y * this.w;
  2483. var yz = this.y * this.z;
  2484. var xw = this.x * this.w;
  2485. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2486. result.m[1] = 2.0 * (xy + zw);
  2487. result.m[2] = 2.0 * (zx - yw);
  2488. result.m[3] = 0;
  2489. result.m[4] = 2.0 * (xy - zw);
  2490. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2491. result.m[6] = 2.0 * (yz + xw);
  2492. result.m[7] = 0;
  2493. result.m[8] = 2.0 * (zx + yw);
  2494. result.m[9] = 2.0 * (yz - xw);
  2495. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2496. result.m[11] = 0;
  2497. result.m[12] = 0;
  2498. result.m[13] = 0;
  2499. result.m[14] = 0;
  2500. result.m[15] = 1.0;
  2501. result._markAsUpdated();
  2502. return this;
  2503. };
  2504. /**
  2505. * Updates the current Quaternion from the passed rotation matrix values.
  2506. * Returns the updated Quaternion.
  2507. */
  2508. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2509. Quaternion.FromRotationMatrixToRef(matrix, this);
  2510. return this;
  2511. };
  2512. // Statics
  2513. /**
  2514. * Returns a new Quaternion set from the passed rotation matrix values.
  2515. */
  2516. Quaternion.FromRotationMatrix = function (matrix) {
  2517. var result = new Quaternion();
  2518. Quaternion.FromRotationMatrixToRef(matrix, result);
  2519. return result;
  2520. };
  2521. /**
  2522. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2523. */
  2524. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2525. var data = matrix.m;
  2526. var m11 = data[0], m12 = data[4], m13 = data[8];
  2527. var m21 = data[1], m22 = data[5], m23 = data[9];
  2528. var m31 = data[2], m32 = data[6], m33 = data[10];
  2529. var trace = m11 + m22 + m33;
  2530. var s;
  2531. if (trace > 0) {
  2532. s = 0.5 / Math.sqrt(trace + 1.0);
  2533. result.w = 0.25 / s;
  2534. result.x = (m32 - m23) * s;
  2535. result.y = (m13 - m31) * s;
  2536. result.z = (m21 - m12) * s;
  2537. }
  2538. else if (m11 > m22 && m11 > m33) {
  2539. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2540. result.w = (m32 - m23) / s;
  2541. result.x = 0.25 * s;
  2542. result.y = (m12 + m21) / s;
  2543. result.z = (m13 + m31) / s;
  2544. }
  2545. else if (m22 > m33) {
  2546. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2547. result.w = (m13 - m31) / s;
  2548. result.x = (m12 + m21) / s;
  2549. result.y = 0.25 * s;
  2550. result.z = (m23 + m32) / s;
  2551. }
  2552. else {
  2553. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2554. result.w = (m21 - m12) / s;
  2555. result.x = (m13 + m31) / s;
  2556. result.y = (m23 + m32) / s;
  2557. result.z = 0.25 * s;
  2558. }
  2559. };
  2560. /**
  2561. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2562. */
  2563. Quaternion.Zero = function () {
  2564. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2565. };
  2566. /**
  2567. * Returns a new Quaternion as the inverted current Quaternion.
  2568. */
  2569. Quaternion.Inverse = function (q) {
  2570. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2571. };
  2572. /**
  2573. * Returns the identity Quaternion.
  2574. */
  2575. Quaternion.Identity = function () {
  2576. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2577. };
  2578. Quaternion.IsIdentity = function (quaternion) {
  2579. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2580. };
  2581. /**
  2582. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2583. */
  2584. Quaternion.RotationAxis = function (axis, angle) {
  2585. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2586. };
  2587. /**
  2588. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2589. */
  2590. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2591. var sin = Math.sin(angle / 2);
  2592. axis.normalize();
  2593. result.w = Math.cos(angle / 2);
  2594. result.x = axis.x * sin;
  2595. result.y = axis.y * sin;
  2596. result.z = axis.z * sin;
  2597. return result;
  2598. };
  2599. /**
  2600. * Retuns a new Quaternion set from the starting index of the passed array.
  2601. */
  2602. Quaternion.FromArray = function (array, offset) {
  2603. if (!offset) {
  2604. offset = 0;
  2605. }
  2606. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2607. };
  2608. /**
  2609. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2610. */
  2611. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2612. var q = new Quaternion();
  2613. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2614. return q;
  2615. };
  2616. /**
  2617. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2618. */
  2619. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2620. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2621. var halfRoll = roll * 0.5;
  2622. var halfPitch = pitch * 0.5;
  2623. var halfYaw = yaw * 0.5;
  2624. var sinRoll = Math.sin(halfRoll);
  2625. var cosRoll = Math.cos(halfRoll);
  2626. var sinPitch = Math.sin(halfPitch);
  2627. var cosPitch = Math.cos(halfPitch);
  2628. var sinYaw = Math.sin(halfYaw);
  2629. var cosYaw = Math.cos(halfYaw);
  2630. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2631. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2632. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2633. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2634. };
  2635. /**
  2636. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2637. */
  2638. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2639. var result = new Quaternion();
  2640. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2641. return result;
  2642. };
  2643. /**
  2644. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2645. */
  2646. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2647. // Produces a quaternion from Euler angles in the z-x-z orientation
  2648. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2649. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2650. var halfBeta = beta * 0.5;
  2651. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2652. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2653. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2654. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2655. };
  2656. /**
  2657. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2658. * cf to Vector3.RotationFromAxis() documentation.
  2659. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2660. */
  2661. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2662. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2663. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2664. return quat;
  2665. };
  2666. /**
  2667. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2668. * cf to Vector3.RotationFromAxis() documentation.
  2669. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2670. */
  2671. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2672. var rotMat = MathTmp.Matrix[0];
  2673. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2674. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2675. };
  2676. Quaternion.Slerp = function (left, right, amount) {
  2677. var result = Quaternion.Identity();
  2678. Quaternion.SlerpToRef(left, right, amount, result);
  2679. return result;
  2680. };
  2681. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2682. var num2;
  2683. var num3;
  2684. var num = amount;
  2685. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2686. var flag = false;
  2687. if (num4 < 0) {
  2688. flag = true;
  2689. num4 = -num4;
  2690. }
  2691. if (num4 > 0.999999) {
  2692. num3 = 1 - num;
  2693. num2 = flag ? -num : num;
  2694. }
  2695. else {
  2696. var num5 = Math.acos(num4);
  2697. var num6 = (1.0 / Math.sin(num5));
  2698. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2699. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2700. }
  2701. result.x = (num3 * left.x) + (num2 * right.x);
  2702. result.y = (num3 * left.y) + (num2 * right.y);
  2703. result.z = (num3 * left.z) + (num2 * right.z);
  2704. result.w = (num3 * left.w) + (num2 * right.w);
  2705. };
  2706. /**
  2707. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2708. */
  2709. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2710. var squared = amount * amount;
  2711. var cubed = amount * squared;
  2712. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2713. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2714. var part3 = (cubed - (2.0 * squared)) + amount;
  2715. var part4 = cubed - squared;
  2716. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2717. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2718. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2719. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2720. return new Quaternion(x, y, z, w);
  2721. };
  2722. return Quaternion;
  2723. }());
  2724. BABYLON.Quaternion = Quaternion;
  2725. var Matrix = (function () {
  2726. function Matrix() {
  2727. this.m = new Float32Array(16);
  2728. this._markAsUpdated();
  2729. }
  2730. Matrix.prototype._markAsUpdated = function () {
  2731. this.updateFlag = Matrix._updateFlagSeed++;
  2732. };
  2733. // Properties
  2734. /**
  2735. * Boolean : True is the matrix is the identity matrix
  2736. */
  2737. Matrix.prototype.isIdentity = function () {
  2738. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2739. return false;
  2740. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2741. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2742. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2743. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2744. return false;
  2745. return true;
  2746. };
  2747. /**
  2748. * Returns the matrix determinant (float).
  2749. */
  2750. Matrix.prototype.determinant = function () {
  2751. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2752. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2753. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2754. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2755. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2756. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2757. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2758. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2759. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2760. };
  2761. // Methods
  2762. /**
  2763. * Returns the matrix underlying array.
  2764. */
  2765. Matrix.prototype.toArray = function () {
  2766. return this.m;
  2767. };
  2768. /**
  2769. * Returns the matrix underlying array.
  2770. */
  2771. Matrix.prototype.asArray = function () {
  2772. return this.toArray();
  2773. };
  2774. /**
  2775. * Inverts in place the Matrix.
  2776. * Returns the Matrix inverted.
  2777. */
  2778. Matrix.prototype.invert = function () {
  2779. this.invertToRef(this);
  2780. return this;
  2781. };
  2782. /**
  2783. * Sets all the matrix elements to zero.
  2784. * Returns the Matrix.
  2785. */
  2786. Matrix.prototype.reset = function () {
  2787. for (var index = 0; index < 16; index++) {
  2788. this.m[index] = 0.0;
  2789. }
  2790. this._markAsUpdated();
  2791. return this;
  2792. };
  2793. /**
  2794. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2795. */
  2796. Matrix.prototype.add = function (other) {
  2797. var result = new Matrix();
  2798. this.addToRef(other, result);
  2799. return result;
  2800. };
  2801. /**
  2802. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2803. * Returns the Matrix.
  2804. */
  2805. Matrix.prototype.addToRef = function (other, result) {
  2806. for (var index = 0; index < 16; index++) {
  2807. result.m[index] = this.m[index] + other.m[index];
  2808. }
  2809. result._markAsUpdated();
  2810. return this;
  2811. };
  2812. /**
  2813. * Adds in place the passed matrix to the current Matrix.
  2814. * Returns the updated Matrix.
  2815. */
  2816. Matrix.prototype.addToSelf = function (other) {
  2817. for (var index = 0; index < 16; index++) {
  2818. this.m[index] += other.m[index];
  2819. }
  2820. this._markAsUpdated();
  2821. return this;
  2822. };
  2823. /**
  2824. * Sets the passed matrix with the current inverted Matrix.
  2825. * Returns the unmodified current Matrix.
  2826. */
  2827. Matrix.prototype.invertToRef = function (other) {
  2828. var l1 = this.m[0];
  2829. var l2 = this.m[1];
  2830. var l3 = this.m[2];
  2831. var l4 = this.m[3];
  2832. var l5 = this.m[4];
  2833. var l6 = this.m[5];
  2834. var l7 = this.m[6];
  2835. var l8 = this.m[7];
  2836. var l9 = this.m[8];
  2837. var l10 = this.m[9];
  2838. var l11 = this.m[10];
  2839. var l12 = this.m[11];
  2840. var l13 = this.m[12];
  2841. var l14 = this.m[13];
  2842. var l15 = this.m[14];
  2843. var l16 = this.m[15];
  2844. var l17 = (l11 * l16) - (l12 * l15);
  2845. var l18 = (l10 * l16) - (l12 * l14);
  2846. var l19 = (l10 * l15) - (l11 * l14);
  2847. var l20 = (l9 * l16) - (l12 * l13);
  2848. var l21 = (l9 * l15) - (l11 * l13);
  2849. var l22 = (l9 * l14) - (l10 * l13);
  2850. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2851. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2852. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2853. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2854. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2855. var l28 = (l7 * l16) - (l8 * l15);
  2856. var l29 = (l6 * l16) - (l8 * l14);
  2857. var l30 = (l6 * l15) - (l7 * l14);
  2858. var l31 = (l5 * l16) - (l8 * l13);
  2859. var l32 = (l5 * l15) - (l7 * l13);
  2860. var l33 = (l5 * l14) - (l6 * l13);
  2861. var l34 = (l7 * l12) - (l8 * l11);
  2862. var l35 = (l6 * l12) - (l8 * l10);
  2863. var l36 = (l6 * l11) - (l7 * l10);
  2864. var l37 = (l5 * l12) - (l8 * l9);
  2865. var l38 = (l5 * l11) - (l7 * l9);
  2866. var l39 = (l5 * l10) - (l6 * l9);
  2867. other.m[0] = l23 * l27;
  2868. other.m[4] = l24 * l27;
  2869. other.m[8] = l25 * l27;
  2870. other.m[12] = l26 * l27;
  2871. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2872. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2873. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2874. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2875. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2876. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2877. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2878. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2879. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2880. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2881. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2882. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2883. other._markAsUpdated();
  2884. return this;
  2885. };
  2886. /**
  2887. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2888. * Returns the updated Matrix.
  2889. */
  2890. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2891. this.m[12] = x;
  2892. this.m[13] = y;
  2893. this.m[14] = z;
  2894. this._markAsUpdated();
  2895. return this;
  2896. };
  2897. /**
  2898. * Inserts the translation vector in the current Matrix.
  2899. * Returns the updated Matrix.
  2900. */
  2901. Matrix.prototype.setTranslation = function (vector3) {
  2902. this.m[12] = vector3.x;
  2903. this.m[13] = vector3.y;
  2904. this.m[14] = vector3.z;
  2905. this._markAsUpdated();
  2906. return this;
  2907. };
  2908. /**
  2909. * Returns a new Vector3 as the extracted translation from the Matrix.
  2910. */
  2911. Matrix.prototype.getTranslation = function () {
  2912. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2913. };
  2914. /**
  2915. * Fill a Vector3 with the extracted translation from the Matrix.
  2916. */
  2917. Matrix.prototype.getTranslationToRef = function (result) {
  2918. result.x = this.m[12];
  2919. result.y = this.m[13];
  2920. result.z = this.m[14];
  2921. return this;
  2922. };
  2923. /**
  2924. * Remove rotation and scaling part from the Matrix.
  2925. * Returns the updated Matrix.
  2926. */
  2927. Matrix.prototype.removeRotationAndScaling = function () {
  2928. this.setRowFromFloats(0, 1, 0, 0, 0);
  2929. this.setRowFromFloats(1, 0, 1, 0, 0);
  2930. this.setRowFromFloats(2, 0, 0, 1, 0);
  2931. return this;
  2932. };
  2933. /**
  2934. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2935. */
  2936. Matrix.prototype.multiply = function (other) {
  2937. var result = new Matrix();
  2938. this.multiplyToRef(other, result);
  2939. return result;
  2940. };
  2941. /**
  2942. * Updates the current Matrix from the passed one values.
  2943. * Returns the updated Matrix.
  2944. */
  2945. Matrix.prototype.copyFrom = function (other) {
  2946. for (var index = 0; index < 16; index++) {
  2947. this.m[index] = other.m[index];
  2948. }
  2949. this._markAsUpdated();
  2950. return this;
  2951. };
  2952. /**
  2953. * Populates the passed array from the starting index with the Matrix values.
  2954. * Returns the Matrix.
  2955. */
  2956. Matrix.prototype.copyToArray = function (array, offset) {
  2957. if (offset === void 0) { offset = 0; }
  2958. for (var index = 0; index < 16; index++) {
  2959. array[offset + index] = this.m[index];
  2960. }
  2961. return this;
  2962. };
  2963. /**
  2964. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2965. */
  2966. Matrix.prototype.multiplyToRef = function (other, result) {
  2967. this.multiplyToArray(other, result.m, 0);
  2968. result._markAsUpdated();
  2969. return this;
  2970. };
  2971. /**
  2972. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2973. */
  2974. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2975. var tm0 = this.m[0];
  2976. var tm1 = this.m[1];
  2977. var tm2 = this.m[2];
  2978. var tm3 = this.m[3];
  2979. var tm4 = this.m[4];
  2980. var tm5 = this.m[5];
  2981. var tm6 = this.m[6];
  2982. var tm7 = this.m[7];
  2983. var tm8 = this.m[8];
  2984. var tm9 = this.m[9];
  2985. var tm10 = this.m[10];
  2986. var tm11 = this.m[11];
  2987. var tm12 = this.m[12];
  2988. var tm13 = this.m[13];
  2989. var tm14 = this.m[14];
  2990. var tm15 = this.m[15];
  2991. var om0 = other.m[0];
  2992. var om1 = other.m[1];
  2993. var om2 = other.m[2];
  2994. var om3 = other.m[3];
  2995. var om4 = other.m[4];
  2996. var om5 = other.m[5];
  2997. var om6 = other.m[6];
  2998. var om7 = other.m[7];
  2999. var om8 = other.m[8];
  3000. var om9 = other.m[9];
  3001. var om10 = other.m[10];
  3002. var om11 = other.m[11];
  3003. var om12 = other.m[12];
  3004. var om13 = other.m[13];
  3005. var om14 = other.m[14];
  3006. var om15 = other.m[15];
  3007. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3008. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3009. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3010. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3011. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3012. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3013. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3014. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3015. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3016. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3017. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3018. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3019. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3020. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3021. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3022. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3023. return this;
  3024. };
  3025. /**
  3026. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3027. */
  3028. Matrix.prototype.equals = function (value) {
  3029. return value &&
  3030. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3031. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3032. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3033. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3034. };
  3035. /**
  3036. * Returns a new Matrix from the current Matrix.
  3037. */
  3038. Matrix.prototype.clone = function () {
  3039. 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]);
  3040. };
  3041. /**
  3042. * Returns the string "Matrix"
  3043. */
  3044. Matrix.prototype.getClassName = function () {
  3045. return "Matrix";
  3046. };
  3047. /**
  3048. * Returns the Matrix hash code.
  3049. */
  3050. Matrix.prototype.getHashCode = function () {
  3051. var hash = this.m[0] || 0;
  3052. for (var i = 1; i < 16; i++) {
  3053. hash = (hash * 397) ^ (this.m[i] || 0);
  3054. }
  3055. return hash;
  3056. };
  3057. /**
  3058. * Decomposes the current Matrix into :
  3059. * - a scale vector3 passed as a reference to update,
  3060. * - a rotation quaternion passed as a reference to update,
  3061. * - a translation vector3 passed as a reference to update.
  3062. * Returns the boolean `true`.
  3063. */
  3064. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3065. translation.x = this.m[12];
  3066. translation.y = this.m[13];
  3067. translation.z = this.m[14];
  3068. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3069. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3070. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3071. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3072. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3073. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3074. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3075. rotation.x = 0;
  3076. rotation.y = 0;
  3077. rotation.z = 0;
  3078. rotation.w = 1;
  3079. return false;
  3080. }
  3081. 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]);
  3082. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3083. return true;
  3084. };
  3085. /**
  3086. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3087. */
  3088. Matrix.prototype.getRotationMatrix = function () {
  3089. var result = Matrix.Identity();
  3090. this.getRotationMatrixToRef(result);
  3091. return result;
  3092. };
  3093. /**
  3094. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3095. * Returns the current Matrix.
  3096. */
  3097. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3098. var m = this.m;
  3099. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3100. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3101. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3102. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3103. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3104. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3105. 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);
  3106. return this;
  3107. };
  3108. // Statics
  3109. /**
  3110. * Returns a new Matrix set from the starting index of the passed array.
  3111. */
  3112. Matrix.FromArray = function (array, offset) {
  3113. var result = new Matrix();
  3114. if (!offset) {
  3115. offset = 0;
  3116. }
  3117. Matrix.FromArrayToRef(array, offset, result);
  3118. return result;
  3119. };
  3120. /**
  3121. * Sets the passed "result" matrix from the starting index of the passed array.
  3122. */
  3123. Matrix.FromArrayToRef = function (array, offset, result) {
  3124. for (var index = 0; index < 16; index++) {
  3125. result.m[index] = array[index + offset];
  3126. }
  3127. result._markAsUpdated();
  3128. };
  3129. /**
  3130. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3131. */
  3132. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3133. for (var index = 0; index < 16; index++) {
  3134. result.m[index] = array[index + offset] * scale;
  3135. }
  3136. result._markAsUpdated();
  3137. };
  3138. /**
  3139. * Sets the passed matrix "result" with the 16 passed floats.
  3140. */
  3141. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3142. result.m[0] = initialM11;
  3143. result.m[1] = initialM12;
  3144. result.m[2] = initialM13;
  3145. result.m[3] = initialM14;
  3146. result.m[4] = initialM21;
  3147. result.m[5] = initialM22;
  3148. result.m[6] = initialM23;
  3149. result.m[7] = initialM24;
  3150. result.m[8] = initialM31;
  3151. result.m[9] = initialM32;
  3152. result.m[10] = initialM33;
  3153. result.m[11] = initialM34;
  3154. result.m[12] = initialM41;
  3155. result.m[13] = initialM42;
  3156. result.m[14] = initialM43;
  3157. result.m[15] = initialM44;
  3158. result._markAsUpdated();
  3159. };
  3160. /**
  3161. * Returns the index-th row of the current matrix as a new Vector4.
  3162. */
  3163. Matrix.prototype.getRow = function (index) {
  3164. if (index < 0 || index > 3) {
  3165. return null;
  3166. }
  3167. var i = index * 4;
  3168. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3169. };
  3170. /**
  3171. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3172. * Returns the updated Matrix.
  3173. */
  3174. Matrix.prototype.setRow = function (index, row) {
  3175. if (index < 0 || index > 3) {
  3176. return this;
  3177. }
  3178. var i = index * 4;
  3179. this.m[i + 0] = row.x;
  3180. this.m[i + 1] = row.y;
  3181. this.m[i + 2] = row.z;
  3182. this.m[i + 3] = row.w;
  3183. this._markAsUpdated();
  3184. return this;
  3185. };
  3186. /**
  3187. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3188. * Returns the updated Matrix.
  3189. */
  3190. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3191. if (index < 0 || index > 3) {
  3192. return this;
  3193. }
  3194. var i = index * 4;
  3195. this.m[i + 0] = x;
  3196. this.m[i + 1] = y;
  3197. this.m[i + 2] = z;
  3198. this.m[i + 3] = w;
  3199. this._markAsUpdated();
  3200. return this;
  3201. };
  3202. /**
  3203. * Returns a new Matrix set from the 16 passed floats.
  3204. */
  3205. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3206. var result = new Matrix();
  3207. result.m[0] = initialM11;
  3208. result.m[1] = initialM12;
  3209. result.m[2] = initialM13;
  3210. result.m[3] = initialM14;
  3211. result.m[4] = initialM21;
  3212. result.m[5] = initialM22;
  3213. result.m[6] = initialM23;
  3214. result.m[7] = initialM24;
  3215. result.m[8] = initialM31;
  3216. result.m[9] = initialM32;
  3217. result.m[10] = initialM33;
  3218. result.m[11] = initialM34;
  3219. result.m[12] = initialM41;
  3220. result.m[13] = initialM42;
  3221. result.m[14] = initialM43;
  3222. result.m[15] = initialM44;
  3223. return result;
  3224. };
  3225. /**
  3226. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3227. */
  3228. Matrix.Compose = function (scale, rotation, translation) {
  3229. var result = Matrix.Identity();
  3230. Matrix.ComposeToRef(scale, rotation, translation, result);
  3231. return result;
  3232. };
  3233. /**
  3234. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3235. */
  3236. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3237. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3238. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3239. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3240. result.setTranslation(translation);
  3241. };
  3242. /**
  3243. * Returns a new indentity Matrix.
  3244. */
  3245. Matrix.Identity = function () {
  3246. 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);
  3247. };
  3248. /**
  3249. * Sets the passed "result" as an identity matrix.
  3250. */
  3251. Matrix.IdentityToRef = function (result) {
  3252. 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);
  3253. };
  3254. /**
  3255. * Returns a new zero Matrix.
  3256. */
  3257. Matrix.Zero = function () {
  3258. 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);
  3259. };
  3260. /**
  3261. * Returns a new rotation matrix for "angle" radians around the X axis.
  3262. */
  3263. Matrix.RotationX = function (angle) {
  3264. var result = new Matrix();
  3265. Matrix.RotationXToRef(angle, result);
  3266. return result;
  3267. };
  3268. /**
  3269. * Returns a new Matrix as the passed inverted one.
  3270. */
  3271. Matrix.Invert = function (source) {
  3272. var result = new Matrix();
  3273. source.invertToRef(result);
  3274. return result;
  3275. };
  3276. /**
  3277. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3278. */
  3279. Matrix.RotationXToRef = function (angle, result) {
  3280. var s = Math.sin(angle);
  3281. var c = Math.cos(angle);
  3282. result.m[0] = 1.0;
  3283. result.m[15] = 1.0;
  3284. result.m[5] = c;
  3285. result.m[10] = c;
  3286. result.m[9] = -s;
  3287. result.m[6] = s;
  3288. result.m[1] = 0.0;
  3289. result.m[2] = 0.0;
  3290. result.m[3] = 0.0;
  3291. result.m[4] = 0.0;
  3292. result.m[7] = 0.0;
  3293. result.m[8] = 0.0;
  3294. result.m[11] = 0.0;
  3295. result.m[12] = 0.0;
  3296. result.m[13] = 0.0;
  3297. result.m[14] = 0.0;
  3298. result._markAsUpdated();
  3299. };
  3300. /**
  3301. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3302. */
  3303. Matrix.RotationY = function (angle) {
  3304. var result = new Matrix();
  3305. Matrix.RotationYToRef(angle, result);
  3306. return result;
  3307. };
  3308. /**
  3309. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3310. */
  3311. Matrix.RotationYToRef = function (angle, result) {
  3312. var s = Math.sin(angle);
  3313. var c = Math.cos(angle);
  3314. result.m[5] = 1.0;
  3315. result.m[15] = 1.0;
  3316. result.m[0] = c;
  3317. result.m[2] = -s;
  3318. result.m[8] = s;
  3319. result.m[10] = c;
  3320. result.m[1] = 0.0;
  3321. result.m[3] = 0.0;
  3322. result.m[4] = 0.0;
  3323. result.m[6] = 0.0;
  3324. result.m[7] = 0.0;
  3325. result.m[9] = 0.0;
  3326. result.m[11] = 0.0;
  3327. result.m[12] = 0.0;
  3328. result.m[13] = 0.0;
  3329. result.m[14] = 0.0;
  3330. result._markAsUpdated();
  3331. };
  3332. /**
  3333. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3334. */
  3335. Matrix.RotationZ = function (angle) {
  3336. var result = new Matrix();
  3337. Matrix.RotationZToRef(angle, result);
  3338. return result;
  3339. };
  3340. /**
  3341. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3342. */
  3343. Matrix.RotationZToRef = function (angle, result) {
  3344. var s = Math.sin(angle);
  3345. var c = Math.cos(angle);
  3346. result.m[10] = 1.0;
  3347. result.m[15] = 1.0;
  3348. result.m[0] = c;
  3349. result.m[1] = s;
  3350. result.m[4] = -s;
  3351. result.m[5] = c;
  3352. result.m[2] = 0.0;
  3353. result.m[3] = 0.0;
  3354. result.m[6] = 0.0;
  3355. result.m[7] = 0.0;
  3356. result.m[8] = 0.0;
  3357. result.m[9] = 0.0;
  3358. result.m[11] = 0.0;
  3359. result.m[12] = 0.0;
  3360. result.m[13] = 0.0;
  3361. result.m[14] = 0.0;
  3362. result._markAsUpdated();
  3363. };
  3364. /**
  3365. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3366. */
  3367. Matrix.RotationAxis = function (axis, angle) {
  3368. var result = Matrix.Zero();
  3369. Matrix.RotationAxisToRef(axis, angle, result);
  3370. return result;
  3371. };
  3372. /**
  3373. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3374. */
  3375. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3376. var s = Math.sin(-angle);
  3377. var c = Math.cos(-angle);
  3378. var c1 = 1 - c;
  3379. axis.normalize();
  3380. result.m[0] = (axis.x * axis.x) * c1 + c;
  3381. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3382. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3383. result.m[3] = 0.0;
  3384. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3385. result.m[5] = (axis.y * axis.y) * c1 + c;
  3386. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3387. result.m[7] = 0.0;
  3388. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3389. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3390. result.m[10] = (axis.z * axis.z) * c1 + c;
  3391. result.m[11] = 0.0;
  3392. result.m[15] = 1.0;
  3393. result._markAsUpdated();
  3394. };
  3395. /**
  3396. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3397. */
  3398. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3399. var result = new Matrix();
  3400. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3401. return result;
  3402. };
  3403. /**
  3404. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3405. */
  3406. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3407. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3408. this._tempQuaternion.toRotationMatrix(result);
  3409. };
  3410. /**
  3411. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3412. */
  3413. Matrix.Scaling = function (x, y, z) {
  3414. var result = Matrix.Zero();
  3415. Matrix.ScalingToRef(x, y, z, result);
  3416. return result;
  3417. };
  3418. /**
  3419. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3420. */
  3421. Matrix.ScalingToRef = function (x, y, z, result) {
  3422. result.m[0] = x;
  3423. result.m[1] = 0.0;
  3424. result.m[2] = 0.0;
  3425. result.m[3] = 0.0;
  3426. result.m[4] = 0.0;
  3427. result.m[5] = y;
  3428. result.m[6] = 0.0;
  3429. result.m[7] = 0.0;
  3430. result.m[8] = 0.0;
  3431. result.m[9] = 0.0;
  3432. result.m[10] = z;
  3433. result.m[11] = 0.0;
  3434. result.m[12] = 0.0;
  3435. result.m[13] = 0.0;
  3436. result.m[14] = 0.0;
  3437. result.m[15] = 1.0;
  3438. result._markAsUpdated();
  3439. };
  3440. /**
  3441. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3442. */
  3443. Matrix.Translation = function (x, y, z) {
  3444. var result = Matrix.Identity();
  3445. Matrix.TranslationToRef(x, y, z, result);
  3446. return result;
  3447. };
  3448. /**
  3449. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3450. */
  3451. Matrix.TranslationToRef = function (x, y, z, result) {
  3452. 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);
  3453. };
  3454. /**
  3455. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3456. */
  3457. Matrix.Lerp = function (startValue, endValue, gradient) {
  3458. var result = Matrix.Zero();
  3459. for (var index = 0; index < 16; index++) {
  3460. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3461. }
  3462. result._markAsUpdated();
  3463. return result;
  3464. };
  3465. /**
  3466. * Returns a new Matrix whose values are computed by :
  3467. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3468. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3469. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3470. */
  3471. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3472. var startScale = new Vector3(0, 0, 0);
  3473. var startRotation = new Quaternion();
  3474. var startTranslation = new Vector3(0, 0, 0);
  3475. startValue.decompose(startScale, startRotation, startTranslation);
  3476. var endScale = new Vector3(0, 0, 0);
  3477. var endRotation = new Quaternion();
  3478. var endTranslation = new Vector3(0, 0, 0);
  3479. endValue.decompose(endScale, endRotation, endTranslation);
  3480. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3481. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3482. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3483. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3484. };
  3485. /**
  3486. * 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".
  3487. * This methods works for a Left-Handed system.
  3488. */
  3489. Matrix.LookAtLH = function (eye, target, up) {
  3490. var result = Matrix.Zero();
  3491. Matrix.LookAtLHToRef(eye, target, up, result);
  3492. return result;
  3493. };
  3494. /**
  3495. * 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".
  3496. * This methods works for a Left-Handed system.
  3497. */
  3498. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3499. // Z axis
  3500. target.subtractToRef(eye, this._zAxis);
  3501. this._zAxis.normalize();
  3502. // X axis
  3503. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3504. if (this._xAxis.lengthSquared() === 0) {
  3505. this._xAxis.x = 1.0;
  3506. }
  3507. else {
  3508. this._xAxis.normalize();
  3509. }
  3510. // Y axis
  3511. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3512. this._yAxis.normalize();
  3513. // Eye angles
  3514. var ex = -Vector3.Dot(this._xAxis, eye);
  3515. var ey = -Vector3.Dot(this._yAxis, eye);
  3516. var ez = -Vector3.Dot(this._zAxis, eye);
  3517. 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);
  3518. };
  3519. /**
  3520. * 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".
  3521. * This methods works for a Right-Handed system.
  3522. */
  3523. Matrix.LookAtRH = function (eye, target, up) {
  3524. var result = Matrix.Zero();
  3525. Matrix.LookAtRHToRef(eye, target, up, result);
  3526. return result;
  3527. };
  3528. /**
  3529. * 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".
  3530. * This methods works for a Left-Handed system.
  3531. */
  3532. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3533. // Z axis
  3534. eye.subtractToRef(target, this._zAxis);
  3535. this._zAxis.normalize();
  3536. // X axis
  3537. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3538. if (this._xAxis.lengthSquared() === 0) {
  3539. this._xAxis.x = 1.0;
  3540. }
  3541. else {
  3542. this._xAxis.normalize();
  3543. }
  3544. // Y axis
  3545. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3546. this._yAxis.normalize();
  3547. // Eye angles
  3548. var ex = -Vector3.Dot(this._xAxis, eye);
  3549. var ey = -Vector3.Dot(this._yAxis, eye);
  3550. var ez = -Vector3.Dot(this._zAxis, eye);
  3551. 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);
  3552. };
  3553. /**
  3554. * 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.
  3555. */
  3556. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3557. var matrix = Matrix.Zero();
  3558. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3559. return matrix;
  3560. };
  3561. /**
  3562. * 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.
  3563. */
  3564. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3565. var n = znear;
  3566. var f = zfar;
  3567. var a = 2.0 / width;
  3568. var b = 2.0 / height;
  3569. var c = 2.0 / (f - n);
  3570. var d = -(f + n) / (f - n);
  3571. 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);
  3572. };
  3573. /**
  3574. * 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.
  3575. */
  3576. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3577. var matrix = Matrix.Zero();
  3578. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3579. return matrix;
  3580. };
  3581. /**
  3582. * 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.
  3583. */
  3584. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3585. var n = znear;
  3586. var f = zfar;
  3587. var a = 2.0 / (right - left);
  3588. var b = 2.0 / (top - bottom);
  3589. var c = 2.0 / (f - n);
  3590. var d = -(f + n) / (f - n);
  3591. var i0 = (left + right) / (left - right);
  3592. var i1 = (top + bottom) / (bottom - top);
  3593. 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);
  3594. };
  3595. /**
  3596. * 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.
  3597. */
  3598. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3599. var matrix = Matrix.Zero();
  3600. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3601. return matrix;
  3602. };
  3603. /**
  3604. * 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.
  3605. */
  3606. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3607. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3608. result.m[10] *= -1.0;
  3609. };
  3610. /**
  3611. * 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.
  3612. */
  3613. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3614. var matrix = Matrix.Zero();
  3615. var n = znear;
  3616. var f = zfar;
  3617. var a = 2.0 * n / width;
  3618. var b = 2.0 * n / height;
  3619. var c = (f + n) / (f - n);
  3620. var d = -2.0 * f * n / (f - n);
  3621. 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);
  3622. return matrix;
  3623. };
  3624. /**
  3625. * 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.
  3626. */
  3627. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3628. var matrix = Matrix.Zero();
  3629. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3630. return matrix;
  3631. };
  3632. /**
  3633. * 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.
  3634. */
  3635. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3636. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3637. var n = znear;
  3638. var f = zfar;
  3639. var t = 1.0 / (Math.tan(fov * 0.5));
  3640. var a = isVerticalFovFixed ? (t / aspect) : t;
  3641. var b = isVerticalFovFixed ? t : (t * aspect);
  3642. var c = (f + n) / (f - n);
  3643. var d = -2.0 * f * n / (f - n);
  3644. 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);
  3645. };
  3646. /**
  3647. * 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.
  3648. */
  3649. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3650. var matrix = Matrix.Zero();
  3651. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3652. return matrix;
  3653. };
  3654. /**
  3655. * 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.
  3656. */
  3657. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3658. //alternatively this could be expressed as:
  3659. // m = PerspectiveFovLHToRef
  3660. // m[10] *= -1.0;
  3661. // m[11] *= -1.0;
  3662. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3663. var n = znear;
  3664. var f = zfar;
  3665. var t = 1.0 / (Math.tan(fov * 0.5));
  3666. var a = isVerticalFovFixed ? (t / aspect) : t;
  3667. var b = isVerticalFovFixed ? t : (t * aspect);
  3668. var c = -(f + n) / (f - n);
  3669. var d = -2 * f * n / (f - n);
  3670. 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);
  3671. };
  3672. /**
  3673. * 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.
  3674. */
  3675. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3676. if (rightHanded === void 0) { rightHanded = false; }
  3677. var rightHandedFactor = rightHanded ? -1 : 1;
  3678. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3679. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3680. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3681. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3682. var xScale = 2.0 / (leftTan + rightTan);
  3683. var yScale = 2.0 / (upTan + downTan);
  3684. result.m[0] = xScale;
  3685. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3686. result.m[5] = yScale;
  3687. result.m[6] = result.m[7] = 0.0;
  3688. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3689. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3690. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3691. result.m[10] = -zfar / (znear - zfar);
  3692. result.m[11] = 1.0 * rightHandedFactor;
  3693. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3694. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3695. // result.m[14] = (znear * zfar) / (znear - zfar);
  3696. result._markAsUpdated();
  3697. };
  3698. /**
  3699. * Returns the final transformation matrix : world * view * projection * viewport
  3700. */
  3701. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3702. var cw = viewport.width;
  3703. var ch = viewport.height;
  3704. var cx = viewport.x;
  3705. var cy = viewport.y;
  3706. 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);
  3707. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3708. };
  3709. /**
  3710. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3711. */
  3712. Matrix.GetAsMatrix2x2 = function (matrix) {
  3713. return new Float32Array([
  3714. matrix.m[0], matrix.m[1],
  3715. matrix.m[4], matrix.m[5]
  3716. ]);
  3717. };
  3718. /**
  3719. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3720. */
  3721. Matrix.GetAsMatrix3x3 = function (matrix) {
  3722. return new Float32Array([
  3723. matrix.m[0], matrix.m[1], matrix.m[2],
  3724. matrix.m[4], matrix.m[5], matrix.m[6],
  3725. matrix.m[8], matrix.m[9], matrix.m[10]
  3726. ]);
  3727. };
  3728. /**
  3729. * Compute the transpose of the passed Matrix.
  3730. * Returns a new Matrix.
  3731. */
  3732. Matrix.Transpose = function (matrix) {
  3733. var result = new Matrix();
  3734. result.m[0] = matrix.m[0];
  3735. result.m[1] = matrix.m[4];
  3736. result.m[2] = matrix.m[8];
  3737. result.m[3] = matrix.m[12];
  3738. result.m[4] = matrix.m[1];
  3739. result.m[5] = matrix.m[5];
  3740. result.m[6] = matrix.m[9];
  3741. result.m[7] = matrix.m[13];
  3742. result.m[8] = matrix.m[2];
  3743. result.m[9] = matrix.m[6];
  3744. result.m[10] = matrix.m[10];
  3745. result.m[11] = matrix.m[14];
  3746. result.m[12] = matrix.m[3];
  3747. result.m[13] = matrix.m[7];
  3748. result.m[14] = matrix.m[11];
  3749. result.m[15] = matrix.m[15];
  3750. return result;
  3751. };
  3752. /**
  3753. * Returns a new Matrix as the reflection matrix across the passed plane.
  3754. */
  3755. Matrix.Reflection = function (plane) {
  3756. var matrix = new Matrix();
  3757. Matrix.ReflectionToRef(plane, matrix);
  3758. return matrix;
  3759. };
  3760. /**
  3761. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3762. */
  3763. Matrix.ReflectionToRef = function (plane, result) {
  3764. plane.normalize();
  3765. var x = plane.normal.x;
  3766. var y = plane.normal.y;
  3767. var z = plane.normal.z;
  3768. var temp = -2 * x;
  3769. var temp2 = -2 * y;
  3770. var temp3 = -2 * z;
  3771. result.m[0] = (temp * x) + 1;
  3772. result.m[1] = temp2 * x;
  3773. result.m[2] = temp3 * x;
  3774. result.m[3] = 0.0;
  3775. result.m[4] = temp * y;
  3776. result.m[5] = (temp2 * y) + 1;
  3777. result.m[6] = temp3 * y;
  3778. result.m[7] = 0.0;
  3779. result.m[8] = temp * z;
  3780. result.m[9] = temp2 * z;
  3781. result.m[10] = (temp3 * z) + 1;
  3782. result.m[11] = 0.0;
  3783. result.m[12] = temp * plane.d;
  3784. result.m[13] = temp2 * plane.d;
  3785. result.m[14] = temp3 * plane.d;
  3786. result.m[15] = 1.0;
  3787. result._markAsUpdated();
  3788. };
  3789. /**
  3790. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3791. */
  3792. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3793. result.m[0] = xaxis.x;
  3794. result.m[1] = xaxis.y;
  3795. result.m[2] = xaxis.z;
  3796. result.m[3] = 0.0;
  3797. result.m[4] = yaxis.x;
  3798. result.m[5] = yaxis.y;
  3799. result.m[6] = yaxis.z;
  3800. result.m[7] = 0.0;
  3801. result.m[8] = zaxis.x;
  3802. result.m[9] = zaxis.y;
  3803. result.m[10] = zaxis.z;
  3804. result.m[11] = 0.0;
  3805. result.m[12] = 0.0;
  3806. result.m[13] = 0.0;
  3807. result.m[14] = 0.0;
  3808. result.m[15] = 1.0;
  3809. result._markAsUpdated();
  3810. };
  3811. /**
  3812. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3813. */
  3814. Matrix.FromQuaternionToRef = function (quat, result) {
  3815. var xx = quat.x * quat.x;
  3816. var yy = quat.y * quat.y;
  3817. var zz = quat.z * quat.z;
  3818. var xy = quat.x * quat.y;
  3819. var zw = quat.z * quat.w;
  3820. var zx = quat.z * quat.x;
  3821. var yw = quat.y * quat.w;
  3822. var yz = quat.y * quat.z;
  3823. var xw = quat.x * quat.w;
  3824. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3825. result.m[1] = 2.0 * (xy + zw);
  3826. result.m[2] = 2.0 * (zx - yw);
  3827. result.m[3] = 0.0;
  3828. result.m[4] = 2.0 * (xy - zw);
  3829. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3830. result.m[6] = 2.0 * (yz + xw);
  3831. result.m[7] = 0.0;
  3832. result.m[8] = 2.0 * (zx + yw);
  3833. result.m[9] = 2.0 * (yz - xw);
  3834. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3835. result.m[11] = 0.0;
  3836. result.m[12] = 0.0;
  3837. result.m[13] = 0.0;
  3838. result.m[14] = 0.0;
  3839. result.m[15] = 1.0;
  3840. result._markAsUpdated();
  3841. };
  3842. return Matrix;
  3843. }());
  3844. Matrix._tempQuaternion = new Quaternion();
  3845. Matrix._xAxis = Vector3.Zero();
  3846. Matrix._yAxis = Vector3.Zero();
  3847. Matrix._zAxis = Vector3.Zero();
  3848. Matrix._updateFlagSeed = 0;
  3849. BABYLON.Matrix = Matrix;
  3850. var Plane = (function () {
  3851. /**
  3852. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3853. */
  3854. function Plane(a, b, c, d) {
  3855. this.normal = new Vector3(a, b, c);
  3856. this.d = d;
  3857. }
  3858. /**
  3859. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3860. */
  3861. Plane.prototype.asArray = function () {
  3862. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3863. };
  3864. // Methods
  3865. /**
  3866. * Returns a new plane copied from the current Plane.
  3867. */
  3868. Plane.prototype.clone = function () {
  3869. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3870. };
  3871. /**
  3872. * Returns the string "Plane".
  3873. */
  3874. Plane.prototype.getClassName = function () {
  3875. return "Plane";
  3876. };
  3877. /**
  3878. * Returns the Plane hash code.
  3879. */
  3880. Plane.prototype.getHashCode = function () {
  3881. var hash = this.normal.getHashCode();
  3882. hash = (hash * 397) ^ (this.d || 0);
  3883. return hash;
  3884. };
  3885. /**
  3886. * Normalize the current Plane in place.
  3887. * Returns the updated Plane.
  3888. */
  3889. Plane.prototype.normalize = function () {
  3890. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3891. var magnitude = 0.0;
  3892. if (norm !== 0) {
  3893. magnitude = 1.0 / norm;
  3894. }
  3895. this.normal.x *= magnitude;
  3896. this.normal.y *= magnitude;
  3897. this.normal.z *= magnitude;
  3898. this.d *= magnitude;
  3899. return this;
  3900. };
  3901. /**
  3902. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3903. */
  3904. Plane.prototype.transform = function (transformation) {
  3905. var transposedMatrix = Matrix.Transpose(transformation);
  3906. var x = this.normal.x;
  3907. var y = this.normal.y;
  3908. var z = this.normal.z;
  3909. var d = this.d;
  3910. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3911. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3912. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3913. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3914. return new Plane(normalX, normalY, normalZ, finalD);
  3915. };
  3916. /**
  3917. * Returns the dot product (float) of the point coordinates and the plane normal.
  3918. */
  3919. Plane.prototype.dotCoordinate = function (point) {
  3920. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3921. };
  3922. /**
  3923. * Updates the current Plane from the plane defined by the three passed points.
  3924. * Returns the updated Plane.
  3925. */
  3926. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3927. var x1 = point2.x - point1.x;
  3928. var y1 = point2.y - point1.y;
  3929. var z1 = point2.z - point1.z;
  3930. var x2 = point3.x - point1.x;
  3931. var y2 = point3.y - point1.y;
  3932. var z2 = point3.z - point1.z;
  3933. var yz = (y1 * z2) - (z1 * y2);
  3934. var xz = (z1 * x2) - (x1 * z2);
  3935. var xy = (x1 * y2) - (y1 * x2);
  3936. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3937. var invPyth;
  3938. if (pyth !== 0) {
  3939. invPyth = 1.0 / pyth;
  3940. }
  3941. else {
  3942. invPyth = 0.0;
  3943. }
  3944. this.normal.x = yz * invPyth;
  3945. this.normal.y = xz * invPyth;
  3946. this.normal.z = xy * invPyth;
  3947. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3948. return this;
  3949. };
  3950. /**
  3951. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3952. */
  3953. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3954. var dot = Vector3.Dot(this.normal, direction);
  3955. return (dot <= epsilon);
  3956. };
  3957. /**
  3958. * Returns the signed distance (float) from the passed point to the Plane.
  3959. */
  3960. Plane.prototype.signedDistanceTo = function (point) {
  3961. return Vector3.Dot(point, this.normal) + this.d;
  3962. };
  3963. // Statics
  3964. /**
  3965. * Returns a new Plane from the passed array.
  3966. */
  3967. Plane.FromArray = function (array) {
  3968. return new Plane(array[0], array[1], array[2], array[3]);
  3969. };
  3970. /**
  3971. * Returns a new Plane defined by the three passed points.
  3972. */
  3973. Plane.FromPoints = function (point1, point2, point3) {
  3974. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3975. result.copyFromPoints(point1, point2, point3);
  3976. return result;
  3977. };
  3978. /**
  3979. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3980. * Note : the vector "normal" is updated because normalized.
  3981. */
  3982. Plane.FromPositionAndNormal = function (origin, normal) {
  3983. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3984. normal.normalize();
  3985. result.normal = normal;
  3986. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3987. return result;
  3988. };
  3989. /**
  3990. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3991. */
  3992. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3993. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3994. return Vector3.Dot(point, normal) + d;
  3995. };
  3996. return Plane;
  3997. }());
  3998. BABYLON.Plane = Plane;
  3999. var Viewport = (function () {
  4000. /**
  4001. * Creates a Viewport object located at (x, y) and sized (width, height).
  4002. */
  4003. function Viewport(x, y, width, height) {
  4004. this.x = x;
  4005. this.y = y;
  4006. this.width = width;
  4007. this.height = height;
  4008. }
  4009. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  4010. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4011. };
  4012. /**
  4013. * Returns a new Viewport copied from the current one.
  4014. */
  4015. Viewport.prototype.clone = function () {
  4016. return new Viewport(this.x, this.y, this.width, this.height);
  4017. };
  4018. return Viewport;
  4019. }());
  4020. BABYLON.Viewport = Viewport;
  4021. var Frustum = (function () {
  4022. function Frustum() {
  4023. }
  4024. /**
  4025. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4026. */
  4027. Frustum.GetPlanes = function (transform) {
  4028. var frustumPlanes = [];
  4029. for (var index = 0; index < 6; index++) {
  4030. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4031. }
  4032. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4033. return frustumPlanes;
  4034. };
  4035. /**
  4036. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4037. */
  4038. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4039. // Near
  4040. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4041. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4042. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4043. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4044. frustumPlanes[0].normalize();
  4045. // Far
  4046. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4047. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4048. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4049. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4050. frustumPlanes[1].normalize();
  4051. // Left
  4052. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4053. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4054. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4055. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4056. frustumPlanes[2].normalize();
  4057. // Right
  4058. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4059. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4060. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4061. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4062. frustumPlanes[3].normalize();
  4063. // Top
  4064. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4065. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4066. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4067. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4068. frustumPlanes[4].normalize();
  4069. // Bottom
  4070. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4071. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4072. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4073. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4074. frustumPlanes[5].normalize();
  4075. };
  4076. return Frustum;
  4077. }());
  4078. BABYLON.Frustum = Frustum;
  4079. var Space;
  4080. (function (Space) {
  4081. Space[Space["LOCAL"] = 0] = "LOCAL";
  4082. Space[Space["WORLD"] = 1] = "WORLD";
  4083. Space[Space["BONE"] = 2] = "BONE";
  4084. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4085. var Axis = (function () {
  4086. function Axis() {
  4087. }
  4088. return Axis;
  4089. }());
  4090. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4091. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4092. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4093. BABYLON.Axis = Axis;
  4094. ;
  4095. var BezierCurve = (function () {
  4096. function BezierCurve() {
  4097. }
  4098. /**
  4099. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4100. */
  4101. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4102. // Extract X (which is equal to time here)
  4103. var f0 = 1 - 3 * x2 + 3 * x1;
  4104. var f1 = 3 * x2 - 6 * x1;
  4105. var f2 = 3 * x1;
  4106. var refinedT = t;
  4107. for (var i = 0; i < 5; i++) {
  4108. var refinedT2 = refinedT * refinedT;
  4109. var refinedT3 = refinedT2 * refinedT;
  4110. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4111. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4112. refinedT -= (x - t) * slope;
  4113. refinedT = Math.min(1, Math.max(0, refinedT));
  4114. }
  4115. // Resolve cubic bezier for the given x
  4116. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4117. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4118. Math.pow(refinedT, 3);
  4119. };
  4120. return BezierCurve;
  4121. }());
  4122. BABYLON.BezierCurve = BezierCurve;
  4123. var Orientation;
  4124. (function (Orientation) {
  4125. Orientation[Orientation["CW"] = 0] = "CW";
  4126. Orientation[Orientation["CCW"] = 1] = "CCW";
  4127. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4128. var Angle = (function () {
  4129. /**
  4130. * Creates an Angle object of "radians" radians (float).
  4131. */
  4132. function Angle(radians) {
  4133. var _this = this;
  4134. /**
  4135. * Returns the Angle value in degrees (float).
  4136. */
  4137. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4138. /**
  4139. * Returns the Angle value in radians (float).
  4140. */
  4141. this.radians = function () { return _this._radians; };
  4142. this._radians = radians;
  4143. if (this._radians < 0.0)
  4144. this._radians += (2.0 * Math.PI);
  4145. }
  4146. /**
  4147. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4148. */
  4149. Angle.BetweenTwoPoints = function (a, b) {
  4150. var delta = b.subtract(a);
  4151. var theta = Math.atan2(delta.y, delta.x);
  4152. return new Angle(theta);
  4153. };
  4154. /**
  4155. * Returns a new Angle object from the passed float in radians.
  4156. */
  4157. Angle.FromRadians = function (radians) {
  4158. return new Angle(radians);
  4159. };
  4160. /**
  4161. * Returns a new Angle object from the passed float in degrees.
  4162. */
  4163. Angle.FromDegrees = function (degrees) {
  4164. return new Angle(degrees * Math.PI / 180.0);
  4165. };
  4166. return Angle;
  4167. }());
  4168. BABYLON.Angle = Angle;
  4169. var Arc2 = (function () {
  4170. /**
  4171. * Creates an Arc object from the three passed points : start, middle and end.
  4172. */
  4173. function Arc2(startPoint, midPoint, endPoint) {
  4174. this.startPoint = startPoint;
  4175. this.midPoint = midPoint;
  4176. this.endPoint = endPoint;
  4177. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4178. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4179. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4180. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4181. 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);
  4182. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4183. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4184. var a1 = this.startAngle.degrees();
  4185. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4186. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4187. // angles correction
  4188. if (a2 - a1 > +180.0)
  4189. a2 -= 360.0;
  4190. if (a2 - a1 < -180.0)
  4191. a2 += 360.0;
  4192. if (a3 - a2 > +180.0)
  4193. a3 -= 360.0;
  4194. if (a3 - a2 < -180.0)
  4195. a3 += 360.0;
  4196. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4197. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4198. }
  4199. return Arc2;
  4200. }());
  4201. BABYLON.Arc2 = Arc2;
  4202. var Path2 = (function () {
  4203. /**
  4204. * Creates a Path2 object from the starting 2D coordinates x and y.
  4205. */
  4206. function Path2(x, y) {
  4207. this._points = new Array();
  4208. this._length = 0.0;
  4209. this.closed = false;
  4210. this._points.push(new Vector2(x, y));
  4211. }
  4212. /**
  4213. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4214. * Returns the updated Path2.
  4215. */
  4216. Path2.prototype.addLineTo = function (x, y) {
  4217. if (closed) {
  4218. //Tools.Error("cannot add lines to closed paths");
  4219. return this;
  4220. }
  4221. var newPoint = new Vector2(x, y);
  4222. var previousPoint = this._points[this._points.length - 1];
  4223. this._points.push(newPoint);
  4224. this._length += newPoint.subtract(previousPoint).length();
  4225. return this;
  4226. };
  4227. /**
  4228. * 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.
  4229. * Returns the updated Path2.
  4230. */
  4231. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4232. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4233. if (closed) {
  4234. //Tools.Error("cannot add arcs to closed paths");
  4235. return this;
  4236. }
  4237. var startPoint = this._points[this._points.length - 1];
  4238. var midPoint = new Vector2(midX, midY);
  4239. var endPoint = new Vector2(endX, endY);
  4240. var arc = new Arc2(startPoint, midPoint, endPoint);
  4241. var increment = arc.angle.radians() / numberOfSegments;
  4242. if (arc.orientation === Orientation.CW)
  4243. increment *= -1;
  4244. var currentAngle = arc.startAngle.radians() + increment;
  4245. for (var i = 0; i < numberOfSegments; i++) {
  4246. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4247. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4248. this.addLineTo(x, y);
  4249. currentAngle += increment;
  4250. }
  4251. return this;
  4252. };
  4253. /**
  4254. * Closes the Path2.
  4255. * Returns the Path2.
  4256. */
  4257. Path2.prototype.close = function () {
  4258. this.closed = true;
  4259. return this;
  4260. };
  4261. /**
  4262. * Returns the Path2 total length (float).
  4263. */
  4264. Path2.prototype.length = function () {
  4265. var result = this._length;
  4266. if (!this.closed) {
  4267. var lastPoint = this._points[this._points.length - 1];
  4268. var firstPoint = this._points[0];
  4269. result += (firstPoint.subtract(lastPoint).length());
  4270. }
  4271. return result;
  4272. };
  4273. /**
  4274. * Returns the Path2 internal array of points.
  4275. */
  4276. Path2.prototype.getPoints = function () {
  4277. return this._points;
  4278. };
  4279. /**
  4280. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4281. */
  4282. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4283. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4284. //Tools.Error("normalized length position should be between 0 and 1.");
  4285. return Vector2.Zero();
  4286. }
  4287. var lengthPosition = normalizedLengthPosition * this.length();
  4288. var previousOffset = 0;
  4289. for (var i = 0; i < this._points.length; i++) {
  4290. var j = (i + 1) % this._points.length;
  4291. var a = this._points[i];
  4292. var b = this._points[j];
  4293. var bToA = b.subtract(a);
  4294. var nextOffset = (bToA.length() + previousOffset);
  4295. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4296. var dir = bToA.normalize();
  4297. var localOffset = lengthPosition - previousOffset;
  4298. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4299. }
  4300. previousOffset = nextOffset;
  4301. }
  4302. //Tools.Error("internal error");
  4303. return Vector2.Zero();
  4304. };
  4305. /**
  4306. * Returns a new Path2 starting at the coordinates (x, y).
  4307. */
  4308. Path2.StartingAt = function (x, y) {
  4309. return new Path2(x, y);
  4310. };
  4311. return Path2;
  4312. }());
  4313. BABYLON.Path2 = Path2;
  4314. var Path3D = (function () {
  4315. /**
  4316. * new Path3D(path, normal, raw)
  4317. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4318. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4319. * path : an array of Vector3, the curve axis of the Path3D
  4320. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4321. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4322. */
  4323. function Path3D(path, firstNormal, raw) {
  4324. this.path = path;
  4325. this._curve = new Array();
  4326. this._distances = new Array();
  4327. this._tangents = new Array();
  4328. this._normals = new Array();
  4329. this._binormals = new Array();
  4330. for (var p = 0; p < path.length; p++) {
  4331. this._curve[p] = path[p].clone(); // hard copy
  4332. }
  4333. this._raw = raw || false;
  4334. this._compute(firstNormal);
  4335. }
  4336. /**
  4337. * Returns the Path3D array of successive Vector3 designing its curve.
  4338. */
  4339. Path3D.prototype.getCurve = function () {
  4340. return this._curve;
  4341. };
  4342. /**
  4343. * Returns an array populated with tangent vectors on each Path3D curve point.
  4344. */
  4345. Path3D.prototype.getTangents = function () {
  4346. return this._tangents;
  4347. };
  4348. /**
  4349. * Returns an array populated with normal vectors on each Path3D curve point.
  4350. */
  4351. Path3D.prototype.getNormals = function () {
  4352. return this._normals;
  4353. };
  4354. /**
  4355. * Returns an array populated with binormal vectors on each Path3D curve point.
  4356. */
  4357. Path3D.prototype.getBinormals = function () {
  4358. return this._binormals;
  4359. };
  4360. /**
  4361. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4362. */
  4363. Path3D.prototype.getDistances = function () {
  4364. return this._distances;
  4365. };
  4366. /**
  4367. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4368. * Returns the same object updated.
  4369. */
  4370. Path3D.prototype.update = function (path, firstNormal) {
  4371. for (var p = 0; p < path.length; p++) {
  4372. this._curve[p].x = path[p].x;
  4373. this._curve[p].y = path[p].y;
  4374. this._curve[p].z = path[p].z;
  4375. }
  4376. this._compute(firstNormal);
  4377. return this;
  4378. };
  4379. // private function compute() : computes tangents, normals and binormals
  4380. Path3D.prototype._compute = function (firstNormal) {
  4381. var l = this._curve.length;
  4382. // first and last tangents
  4383. this._tangents[0] = this._getFirstNonNullVector(0);
  4384. if (!this._raw) {
  4385. this._tangents[0].normalize();
  4386. }
  4387. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4388. if (!this._raw) {
  4389. this._tangents[l - 1].normalize();
  4390. }
  4391. // normals and binormals at first point : arbitrary vector with _normalVector()
  4392. var tg0 = this._tangents[0];
  4393. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4394. this._normals[0] = pp0;
  4395. if (!this._raw) {
  4396. this._normals[0].normalize();
  4397. }
  4398. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4399. if (!this._raw) {
  4400. this._binormals[0].normalize();
  4401. }
  4402. this._distances[0] = 0.0;
  4403. // normals and binormals : next points
  4404. var prev; // previous vector (segment)
  4405. var cur; // current vector (segment)
  4406. var curTang; // current tangent
  4407. // previous normal
  4408. var prevBinor; // previous binormal
  4409. for (var i = 1; i < l; i++) {
  4410. // tangents
  4411. prev = this._getLastNonNullVector(i);
  4412. if (i < l - 1) {
  4413. cur = this._getFirstNonNullVector(i);
  4414. this._tangents[i] = prev.add(cur);
  4415. this._tangents[i].normalize();
  4416. }
  4417. this._distances[i] = this._distances[i - 1] + prev.length();
  4418. // normals and binormals
  4419. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4420. curTang = this._tangents[i];
  4421. prevBinor = this._binormals[i - 1];
  4422. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4423. if (!this._raw) {
  4424. this._normals[i].normalize();
  4425. }
  4426. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4427. if (!this._raw) {
  4428. this._binormals[i].normalize();
  4429. }
  4430. }
  4431. };
  4432. // private function getFirstNonNullVector(index)
  4433. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4434. Path3D.prototype._getFirstNonNullVector = function (index) {
  4435. var i = 1;
  4436. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4437. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4438. i++;
  4439. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4440. }
  4441. return nNVector;
  4442. };
  4443. // private function getLastNonNullVector(index)
  4444. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4445. Path3D.prototype._getLastNonNullVector = function (index) {
  4446. var i = 1;
  4447. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4448. while (nLVector.length() === 0 && index > i + 1) {
  4449. i++;
  4450. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4451. }
  4452. return nLVector;
  4453. };
  4454. // private function normalVector(v0, vt, va) :
  4455. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4456. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4457. Path3D.prototype._normalVector = function (v0, vt, va) {
  4458. var normal0;
  4459. var tgl = vt.length();
  4460. if (tgl === 0.0) {
  4461. tgl = 1.0;
  4462. }
  4463. if (va === undefined || va === null) {
  4464. var point;
  4465. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4466. point = new Vector3(0.0, -1.0, 0.0);
  4467. }
  4468. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4469. point = new Vector3(1.0, 0.0, 0.0);
  4470. }
  4471. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4472. point = new Vector3(0.0, 0.0, 1.0);
  4473. }
  4474. normal0 = Vector3.Cross(vt, point);
  4475. }
  4476. else {
  4477. normal0 = Vector3.Cross(vt, va);
  4478. Vector3.CrossToRef(normal0, vt, normal0);
  4479. }
  4480. normal0.normalize();
  4481. return normal0;
  4482. };
  4483. return Path3D;
  4484. }());
  4485. BABYLON.Path3D = Path3D;
  4486. var Curve3 = (function () {
  4487. /**
  4488. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4489. * A Curve3 is designed from a series of successive Vector3.
  4490. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4491. */
  4492. function Curve3(points) {
  4493. this._length = 0.0;
  4494. this._points = points;
  4495. this._length = this._computeLength(points);
  4496. }
  4497. /**
  4498. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4499. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4500. * @param v1 (Vector3) the control point
  4501. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4502. * @param nbPoints (integer) the wanted number of points in the curve
  4503. */
  4504. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4505. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4506. var bez = new Array();
  4507. var equation = function (t, val0, val1, val2) {
  4508. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4509. return res;
  4510. };
  4511. for (var i = 0; i <= nbPoints; i++) {
  4512. 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)));
  4513. }
  4514. return new Curve3(bez);
  4515. };
  4516. /**
  4517. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4518. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4519. * @param v1 (Vector3) the first control point
  4520. * @param v2 (Vector3) the second control point
  4521. * @param v3 (Vector3) the end point of the Cubic Bezier
  4522. * @param nbPoints (integer) the wanted number of points in the curve
  4523. */
  4524. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4525. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4526. var bez = new Array();
  4527. var equation = function (t, val0, val1, val2, val3) {
  4528. 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;
  4529. return res;
  4530. };
  4531. for (var i = 0; i <= nbPoints; i++) {
  4532. 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)));
  4533. }
  4534. return new Curve3(bez);
  4535. };
  4536. /**
  4537. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4538. * @param p1 (Vector3) the origin point of the Hermite Spline
  4539. * @param t1 (Vector3) the tangent vector at the origin point
  4540. * @param p2 (Vector3) the end point of the Hermite Spline
  4541. * @param t2 (Vector3) the tangent vector at the end point
  4542. * @param nbPoints (integer) the wanted number of points in the curve
  4543. */
  4544. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4545. var hermite = new Array();
  4546. var step = 1.0 / nbPoints;
  4547. for (var i = 0; i <= nbPoints; i++) {
  4548. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4549. }
  4550. return new Curve3(hermite);
  4551. };
  4552. /**
  4553. * Returns a Curve3 object along a CatmullRom Spline curve :
  4554. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4555. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4556. */
  4557. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4558. var totalPoints = new Array();
  4559. totalPoints.push(points[0].clone());
  4560. Array.prototype.push.apply(totalPoints, points);
  4561. totalPoints.push(points[points.length - 1].clone());
  4562. var catmullRom = new Array();
  4563. var step = 1.0 / nbPoints;
  4564. for (var i = 0; i < totalPoints.length - 3; i++) {
  4565. var amount = 0.0;
  4566. for (var c = 0; c < nbPoints; c++) {
  4567. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4568. amount += step;
  4569. }
  4570. }
  4571. i--;
  4572. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4573. return new Curve3(catmullRom);
  4574. };
  4575. /**
  4576. * Returns the Curve3 stored array of successive Vector3
  4577. */
  4578. Curve3.prototype.getPoints = function () {
  4579. return this._points;
  4580. };
  4581. /**
  4582. * Returns the computed length (float) of the curve.
  4583. */
  4584. Curve3.prototype.length = function () {
  4585. return this._length;
  4586. };
  4587. /**
  4588. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4589. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4590. * curveA and curveB keep unchanged.
  4591. */
  4592. Curve3.prototype.continue = function (curve) {
  4593. var lastPoint = this._points[this._points.length - 1];
  4594. var continuedPoints = this._points.slice();
  4595. var curvePoints = curve.getPoints();
  4596. for (var i = 1; i < curvePoints.length; i++) {
  4597. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4598. }
  4599. var continuedCurve = new Curve3(continuedPoints);
  4600. return continuedCurve;
  4601. };
  4602. Curve3.prototype._computeLength = function (path) {
  4603. var l = 0;
  4604. for (var i = 1; i < path.length; i++) {
  4605. l += (path[i].subtract(path[i - 1])).length();
  4606. }
  4607. return l;
  4608. };
  4609. return Curve3;
  4610. }());
  4611. BABYLON.Curve3 = Curve3;
  4612. // SphericalHarmonics
  4613. var SphericalHarmonics = (function () {
  4614. function SphericalHarmonics() {
  4615. this.L00 = Vector3.Zero();
  4616. this.L1_1 = Vector3.Zero();
  4617. this.L10 = Vector3.Zero();
  4618. this.L11 = Vector3.Zero();
  4619. this.L2_2 = Vector3.Zero();
  4620. this.L2_1 = Vector3.Zero();
  4621. this.L20 = Vector3.Zero();
  4622. this.L21 = Vector3.Zero();
  4623. this.L22 = Vector3.Zero();
  4624. }
  4625. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4626. var colorVector = new Vector3(color.r, color.g, color.b);
  4627. var c = colorVector.scale(deltaSolidAngle);
  4628. this.L00 = this.L00.add(c.scale(0.282095));
  4629. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4630. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4631. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4632. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4633. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4634. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4635. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4636. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4637. };
  4638. SphericalHarmonics.prototype.scale = function (scale) {
  4639. this.L00 = this.L00.scale(scale);
  4640. this.L1_1 = this.L1_1.scale(scale);
  4641. this.L10 = this.L10.scale(scale);
  4642. this.L11 = this.L11.scale(scale);
  4643. this.L2_2 = this.L2_2.scale(scale);
  4644. this.L2_1 = this.L2_1.scale(scale);
  4645. this.L20 = this.L20.scale(scale);
  4646. this.L21 = this.L21.scale(scale);
  4647. this.L22 = this.L22.scale(scale);
  4648. };
  4649. return SphericalHarmonics;
  4650. }());
  4651. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4652. // SphericalPolynomial
  4653. var SphericalPolynomial = (function () {
  4654. function SphericalPolynomial() {
  4655. this.x = Vector3.Zero();
  4656. this.y = Vector3.Zero();
  4657. this.z = Vector3.Zero();
  4658. this.xx = Vector3.Zero();
  4659. this.yy = Vector3.Zero();
  4660. this.zz = Vector3.Zero();
  4661. this.xy = Vector3.Zero();
  4662. this.yz = Vector3.Zero();
  4663. this.zx = Vector3.Zero();
  4664. }
  4665. SphericalPolynomial.prototype.addAmbient = function (color) {
  4666. var colorVector = new Vector3(color.r, color.g, color.b);
  4667. this.xx = this.xx.add(colorVector);
  4668. this.yy = this.yy.add(colorVector);
  4669. this.zz = this.zz.add(colorVector);
  4670. };
  4671. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4672. var result = new SphericalPolynomial();
  4673. result.x = harmonics.L11.scale(1.02333);
  4674. result.y = harmonics.L1_1.scale(1.02333);
  4675. result.z = harmonics.L10.scale(1.02333);
  4676. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4677. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4678. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4679. result.yz = harmonics.L2_1.scale(0.858086);
  4680. result.zx = harmonics.L21.scale(0.858086);
  4681. result.xy = harmonics.L2_2.scale(0.858086);
  4682. return result;
  4683. };
  4684. return SphericalPolynomial;
  4685. }());
  4686. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4687. // Vertex formats
  4688. var PositionNormalVertex = (function () {
  4689. function PositionNormalVertex(position, normal) {
  4690. if (position === void 0) { position = Vector3.Zero(); }
  4691. if (normal === void 0) { normal = Vector3.Up(); }
  4692. this.position = position;
  4693. this.normal = normal;
  4694. }
  4695. PositionNormalVertex.prototype.clone = function () {
  4696. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4697. };
  4698. return PositionNormalVertex;
  4699. }());
  4700. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4701. var PositionNormalTextureVertex = (function () {
  4702. function PositionNormalTextureVertex(position, normal, uv) {
  4703. if (position === void 0) { position = Vector3.Zero(); }
  4704. if (normal === void 0) { normal = Vector3.Up(); }
  4705. if (uv === void 0) { uv = Vector2.Zero(); }
  4706. this.position = position;
  4707. this.normal = normal;
  4708. this.uv = uv;
  4709. }
  4710. PositionNormalTextureVertex.prototype.clone = function () {
  4711. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4712. };
  4713. return PositionNormalTextureVertex;
  4714. }());
  4715. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4716. // Temporary pre-allocated objects for engine internal use
  4717. // usage in any internal function :
  4718. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4719. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4720. var Tmp = (function () {
  4721. function Tmp() {
  4722. }
  4723. return Tmp;
  4724. }());
  4725. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4726. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4727. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4728. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4729. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4730. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4731. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4732. Matrix.Zero(), Matrix.Zero(),
  4733. Matrix.Zero(), Matrix.Zero(),
  4734. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4735. BABYLON.Tmp = Tmp;
  4736. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4737. var MathTmp = (function () {
  4738. function MathTmp() {
  4739. }
  4740. return MathTmp;
  4741. }());
  4742. MathTmp.Vector3 = [Vector3.Zero()];
  4743. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4744. MathTmp.Quaternion = [Quaternion.Zero()];
  4745. })(BABYLON || (BABYLON = {}));
  4746. //# sourceMappingURL=babylon.math.js.map
  4747. //# sourceMappingURL=babylon.mixins.js.map
  4748. var BABYLON;
  4749. (function (BABYLON) {
  4750. function generateSerializableMember(type, sourceName) {
  4751. return function (target, propertyKey) {
  4752. if (!target.__serializableMembers) {
  4753. target.__serializableMembers = {};
  4754. }
  4755. if (!target.__serializableMembers[propertyKey]) {
  4756. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4757. }
  4758. };
  4759. }
  4760. function generateExpandMember(setCallback, targetKey) {
  4761. return function (target, propertyKey) {
  4762. var key = targetKey || ("_" + propertyKey);
  4763. Object.defineProperty(target, propertyKey, {
  4764. get: function () {
  4765. return this[key];
  4766. },
  4767. set: function (value) {
  4768. if (this[key] === value) {
  4769. return;
  4770. }
  4771. this[key] = value;
  4772. target[setCallback].apply(this);
  4773. },
  4774. enumerable: true,
  4775. configurable: true
  4776. });
  4777. };
  4778. }
  4779. function expandToProperty(callback, targetKey) {
  4780. return generateExpandMember(callback, targetKey);
  4781. }
  4782. BABYLON.expandToProperty = expandToProperty;
  4783. function serialize(sourceName) {
  4784. return generateSerializableMember(0, sourceName); // value member
  4785. }
  4786. BABYLON.serialize = serialize;
  4787. function serializeAsTexture(sourceName) {
  4788. return generateSerializableMember(1, sourceName); // texture member
  4789. }
  4790. BABYLON.serializeAsTexture = serializeAsTexture;
  4791. function serializeAsColor3(sourceName) {
  4792. return generateSerializableMember(2, sourceName); // color3 member
  4793. }
  4794. BABYLON.serializeAsColor3 = serializeAsColor3;
  4795. function serializeAsFresnelParameters(sourceName) {
  4796. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4797. }
  4798. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4799. function serializeAsVector2(sourceName) {
  4800. return generateSerializableMember(4, sourceName); // vector2 member
  4801. }
  4802. BABYLON.serializeAsVector2 = serializeAsVector2;
  4803. function serializeAsVector3(sourceName) {
  4804. return generateSerializableMember(5, sourceName); // vector3 member
  4805. }
  4806. BABYLON.serializeAsVector3 = serializeAsVector3;
  4807. function serializeAsMeshReference(sourceName) {
  4808. return generateSerializableMember(6, sourceName); // mesh reference member
  4809. }
  4810. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4811. function serializeAsColorCurves(sourceName) {
  4812. return generateSerializableMember(7, sourceName); // color curves
  4813. }
  4814. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4815. function serializeAsColor4(sourceName) {
  4816. return generateSerializableMember(8, sourceName); // color 4
  4817. }
  4818. BABYLON.serializeAsColor4 = serializeAsColor4;
  4819. function serializeAsImageProcessingConfiguration(sourceName) {
  4820. return generateSerializableMember(9, sourceName); // image processing
  4821. }
  4822. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  4823. var SerializationHelper = (function () {
  4824. function SerializationHelper() {
  4825. }
  4826. SerializationHelper.Serialize = function (entity, serializationObject) {
  4827. if (!serializationObject) {
  4828. serializationObject = {};
  4829. }
  4830. // Tags
  4831. if (BABYLON.Tags) {
  4832. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4833. }
  4834. // Properties
  4835. for (var property in entity.__serializableMembers) {
  4836. var propertyDescriptor = entity.__serializableMembers[property];
  4837. var targetPropertyName = propertyDescriptor.sourceName || property;
  4838. var propertyType = propertyDescriptor.type;
  4839. var sourceProperty = entity[property];
  4840. if (sourceProperty !== undefined && sourceProperty !== null) {
  4841. switch (propertyType) {
  4842. case 0:
  4843. serializationObject[targetPropertyName] = sourceProperty;
  4844. break;
  4845. case 1:
  4846. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4847. break;
  4848. case 2:
  4849. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4850. break;
  4851. case 3:
  4852. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4853. break;
  4854. case 4:
  4855. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4856. break;
  4857. case 5:
  4858. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4859. break;
  4860. case 6:
  4861. serializationObject[targetPropertyName] = sourceProperty.id;
  4862. break;
  4863. case 7:
  4864. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4865. break;
  4866. case 8:
  4867. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4868. break;
  4869. case 9:
  4870. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4871. break;
  4872. }
  4873. }
  4874. }
  4875. return serializationObject;
  4876. };
  4877. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4878. var destination = creationFunction();
  4879. // Tags
  4880. if (BABYLON.Tags) {
  4881. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4882. }
  4883. // Properties
  4884. for (var property in destination.__serializableMembers) {
  4885. var propertyDescriptor = destination.__serializableMembers[property];
  4886. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4887. var propertyType = propertyDescriptor.type;
  4888. if (sourceProperty !== undefined && sourceProperty !== null) {
  4889. switch (propertyType) {
  4890. case 0:
  4891. destination[property] = sourceProperty;
  4892. break;
  4893. case 1:
  4894. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4895. break;
  4896. case 2:
  4897. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4898. break;
  4899. case 3:
  4900. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4901. break;
  4902. case 4:
  4903. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4904. break;
  4905. case 5:
  4906. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4907. break;
  4908. case 6:
  4909. destination[property] = scene.getLastMeshByID(sourceProperty);
  4910. break;
  4911. case 7:
  4912. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4913. break;
  4914. case 8:
  4915. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  4916. break;
  4917. case 9:
  4918. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  4919. break;
  4920. }
  4921. }
  4922. }
  4923. return destination;
  4924. };
  4925. SerializationHelper.Clone = function (creationFunction, source) {
  4926. var destination = creationFunction();
  4927. // Tags
  4928. if (BABYLON.Tags) {
  4929. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4930. }
  4931. // Properties
  4932. for (var property in destination.__serializableMembers) {
  4933. var propertyDescriptor = destination.__serializableMembers[property];
  4934. var sourceProperty = source[property];
  4935. var propertyType = propertyDescriptor.type;
  4936. if (sourceProperty !== undefined && sourceProperty !== null) {
  4937. switch (propertyType) {
  4938. case 0: // Value
  4939. case 6:
  4940. destination[property] = sourceProperty;
  4941. break;
  4942. case 1: // Texture
  4943. case 2: // Color3
  4944. case 3: // FresnelParameters
  4945. case 4: // Vector2
  4946. case 5: // Vector3
  4947. case 7:
  4948. destination[property] = sourceProperty.clone();
  4949. break;
  4950. }
  4951. }
  4952. }
  4953. return destination;
  4954. };
  4955. return SerializationHelper;
  4956. }());
  4957. BABYLON.SerializationHelper = SerializationHelper;
  4958. })(BABYLON || (BABYLON = {}));
  4959. //# sourceMappingURL=babylon.decorators.js.map
  4960. var BABYLON;
  4961. (function (BABYLON) {
  4962. /**
  4963. * A class serves as a medium between the observable and its observers
  4964. */
  4965. var EventState = (function () {
  4966. /**
  4967. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4968. */
  4969. function EventState(mask, skipNextObservers) {
  4970. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4971. this.initalize(mask, skipNextObservers);
  4972. }
  4973. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4974. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4975. this.mask = mask;
  4976. this.skipNextObservers = skipNextObservers;
  4977. return this;
  4978. };
  4979. return EventState;
  4980. }());
  4981. BABYLON.EventState = EventState;
  4982. /**
  4983. * Represent an Observer registered to a given Observable object.
  4984. */
  4985. var Observer = (function () {
  4986. function Observer(callback, mask) {
  4987. this.callback = callback;
  4988. this.mask = mask;
  4989. }
  4990. return Observer;
  4991. }());
  4992. BABYLON.Observer = Observer;
  4993. /**
  4994. * The Observable class is a simple implementation of the Observable pattern.
  4995. * 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.
  4996. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4997. * 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).
  4998. * 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.
  4999. */
  5000. var Observable = (function () {
  5001. function Observable() {
  5002. this._observers = new Array();
  5003. this._eventState = new EventState(0);
  5004. }
  5005. /**
  5006. * Create a new Observer with the specified callback
  5007. * @param callback the callback that will be executed for that Observer
  5008. * @param mask the mask used to filter observers
  5009. * @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.
  5010. */
  5011. Observable.prototype.add = function (callback, mask, insertFirst) {
  5012. if (mask === void 0) { mask = -1; }
  5013. if (insertFirst === void 0) { insertFirst = false; }
  5014. if (!callback) {
  5015. return null;
  5016. }
  5017. var observer = new Observer(callback, mask);
  5018. if (insertFirst) {
  5019. this._observers.unshift(observer);
  5020. }
  5021. else {
  5022. this._observers.push(observer);
  5023. }
  5024. return observer;
  5025. };
  5026. /**
  5027. * Remove an Observer from the Observable object
  5028. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5029. */
  5030. Observable.prototype.remove = function (observer) {
  5031. var index = this._observers.indexOf(observer);
  5032. if (index !== -1) {
  5033. this._observers.splice(index, 1);
  5034. return true;
  5035. }
  5036. return false;
  5037. };
  5038. /**
  5039. * Remove a callback from the Observable object
  5040. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5041. */
  5042. Observable.prototype.removeCallback = function (callback) {
  5043. for (var index = 0; index < this._observers.length; index++) {
  5044. if (this._observers[index].callback === callback) {
  5045. this._observers.splice(index, 1);
  5046. return true;
  5047. }
  5048. }
  5049. return false;
  5050. };
  5051. /**
  5052. * Notify all Observers by calling their respective callback with the given data
  5053. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5054. * @param eventData
  5055. * @param mask
  5056. */
  5057. Observable.prototype.notifyObservers = function (eventData, mask) {
  5058. if (mask === void 0) { mask = -1; }
  5059. var state = this._eventState;
  5060. state.mask = mask;
  5061. state.skipNextObservers = false;
  5062. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5063. var obs = _a[_i];
  5064. if (obs.mask & mask) {
  5065. obs.callback(eventData, state);
  5066. }
  5067. if (state.skipNextObservers) {
  5068. return false;
  5069. }
  5070. }
  5071. return true;
  5072. };
  5073. /**
  5074. * return true is the Observable has at least one Observer registered
  5075. */
  5076. Observable.prototype.hasObservers = function () {
  5077. return this._observers.length > 0;
  5078. };
  5079. /**
  5080. * Clear the list of observers
  5081. */
  5082. Observable.prototype.clear = function () {
  5083. this._observers = new Array();
  5084. };
  5085. /**
  5086. * Clone the current observable
  5087. */
  5088. Observable.prototype.clone = function () {
  5089. var result = new Observable();
  5090. result._observers = this._observers.slice(0);
  5091. return result;
  5092. };
  5093. /**
  5094. * Does this observable handles observer registered with a given mask
  5095. * @param {number} trigger - the mask to be tested
  5096. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5097. **/
  5098. Observable.prototype.hasSpecificMask = function (mask) {
  5099. if (mask === void 0) { mask = -1; }
  5100. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5101. var obs = _a[_i];
  5102. if (obs.mask & mask && obs.mask === mask) {
  5103. return true;
  5104. }
  5105. }
  5106. return false;
  5107. };
  5108. return Observable;
  5109. }());
  5110. BABYLON.Observable = Observable;
  5111. })(BABYLON || (BABYLON = {}));
  5112. //# sourceMappingURL=babylon.observable.js.map
  5113. var BABYLON;
  5114. (function (BABYLON) {
  5115. var SmartArray = (function () {
  5116. function SmartArray(capacity) {
  5117. this.length = 0;
  5118. this._duplicateId = 0;
  5119. this.data = new Array(capacity);
  5120. this._id = SmartArray._GlobalId++;
  5121. }
  5122. SmartArray.prototype.push = function (value) {
  5123. this.data[this.length++] = value;
  5124. if (this.length > this.data.length) {
  5125. this.data.length *= 2;
  5126. }
  5127. if (!value.__smartArrayFlags) {
  5128. value.__smartArrayFlags = {};
  5129. }
  5130. value.__smartArrayFlags[this._id] = this._duplicateId;
  5131. };
  5132. SmartArray.prototype.forEach = function (func) {
  5133. for (var index = 0; index < this.length; index++) {
  5134. func(this.data[index]);
  5135. }
  5136. };
  5137. SmartArray.prototype.pushNoDuplicate = function (value) {
  5138. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5139. return false;
  5140. }
  5141. this.push(value);
  5142. return true;
  5143. };
  5144. SmartArray.prototype.sort = function (compareFn) {
  5145. this.data.sort(compareFn);
  5146. };
  5147. SmartArray.prototype.reset = function () {
  5148. this.length = 0;
  5149. this._duplicateId++;
  5150. };
  5151. SmartArray.prototype.dispose = function () {
  5152. this.reset();
  5153. this.data.length = 0;
  5154. };
  5155. SmartArray.prototype.concat = function (array) {
  5156. if (array.length === 0) {
  5157. return;
  5158. }
  5159. if (this.length + array.length > this.data.length) {
  5160. this.data.length = (this.length + array.length) * 2;
  5161. }
  5162. for (var index = 0; index < array.length; index++) {
  5163. this.data[this.length++] = (array.data || array)[index];
  5164. }
  5165. };
  5166. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5167. if (array.length === 0) {
  5168. return;
  5169. }
  5170. if (this.length + array.length > this.data.length) {
  5171. this.data.length = (this.length + array.length) * 2;
  5172. }
  5173. for (var index = 0; index < array.length; index++) {
  5174. var item = (array.data || array)[index];
  5175. this.pushNoDuplicate(item);
  5176. }
  5177. };
  5178. SmartArray.prototype.indexOf = function (value) {
  5179. var position = this.data.indexOf(value);
  5180. if (position >= this.length) {
  5181. return -1;
  5182. }
  5183. return position;
  5184. };
  5185. SmartArray.prototype.contains = function (value) {
  5186. return this.data.indexOf(value) !== -1;
  5187. };
  5188. return SmartArray;
  5189. }());
  5190. // Statics
  5191. SmartArray._GlobalId = 0;
  5192. BABYLON.SmartArray = SmartArray;
  5193. })(BABYLON || (BABYLON = {}));
  5194. //# sourceMappingURL=babylon.smartArray.js.map
  5195. var BABYLON;
  5196. (function (BABYLON) {
  5197. // Screenshots
  5198. var screenshotCanvas;
  5199. var cloneValue = function (source, destinationObject) {
  5200. if (!source)
  5201. return null;
  5202. if (source instanceof BABYLON.Mesh) {
  5203. return null;
  5204. }
  5205. if (source instanceof BABYLON.SubMesh) {
  5206. return source.clone(destinationObject);
  5207. }
  5208. else if (source.clone) {
  5209. return source.clone();
  5210. }
  5211. return null;
  5212. };
  5213. var Tools = (function () {
  5214. function Tools() {
  5215. }
  5216. ;
  5217. /**
  5218. * Interpolates between a and b via alpha
  5219. * @param a The lower value (returned when alpha = 0)
  5220. * @param b The upper value (returned when alpha = 1)
  5221. * @param alpha The interpolation-factor
  5222. * @return The mixed value
  5223. */
  5224. Tools.Mix = function (a, b, alpha) {
  5225. return a * (1 - alpha) + b * alpha;
  5226. };
  5227. Tools.Instantiate = function (className) {
  5228. var arr = className.split(".");
  5229. var fn = (window || this);
  5230. for (var i = 0, len = arr.length; i < len; i++) {
  5231. fn = fn[arr[i]];
  5232. }
  5233. if (typeof fn !== "function") {
  5234. return null;
  5235. }
  5236. return fn;
  5237. };
  5238. Tools.SetImmediate = function (action) {
  5239. if (window.setImmediate) {
  5240. window.setImmediate(action);
  5241. }
  5242. else {
  5243. setTimeout(action, 1);
  5244. }
  5245. };
  5246. Tools.IsExponentOfTwo = function (value) {
  5247. var count = 1;
  5248. do {
  5249. count *= 2;
  5250. } while (count < value);
  5251. return count === value;
  5252. };
  5253. /**
  5254. * Find the next highest power of two.
  5255. * @param x Number to start search from.
  5256. * @return Next highest power of two.
  5257. */
  5258. Tools.CeilingPOT = function (x) {
  5259. x--;
  5260. x |= x >> 1;
  5261. x |= x >> 2;
  5262. x |= x >> 4;
  5263. x |= x >> 8;
  5264. x |= x >> 16;
  5265. x++;
  5266. return x;
  5267. };
  5268. /**
  5269. * Find the next lowest power of two.
  5270. * @param x Number to start search from.
  5271. * @return Next lowest power of two.
  5272. */
  5273. Tools.FloorPOT = function (x) {
  5274. x = x | (x >> 1);
  5275. x = x | (x >> 2);
  5276. x = x | (x >> 4);
  5277. x = x | (x >> 8);
  5278. x = x | (x >> 16);
  5279. return x - (x >> 1);
  5280. };
  5281. /**
  5282. * Find the nearest power of two.
  5283. * @param x Number to start search from.
  5284. * @return Next nearest power of two.
  5285. */
  5286. Tools.NearestPOT = function (x) {
  5287. var c = Tools.CeilingPOT(x);
  5288. var f = Tools.FloorPOT(x);
  5289. return (c - x) > (x - f) ? f : c;
  5290. };
  5291. Tools.GetExponentOfTwo = function (value, max, mode) {
  5292. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5293. var pot;
  5294. switch (mode) {
  5295. case BABYLON.Engine.SCALEMODE_FLOOR:
  5296. pot = Tools.FloorPOT(value);
  5297. break;
  5298. case BABYLON.Engine.SCALEMODE_NEAREST:
  5299. pot = Tools.NearestPOT(value);
  5300. break;
  5301. case BABYLON.Engine.SCALEMODE_CEILING:
  5302. pot = Tools.CeilingPOT(value);
  5303. break;
  5304. }
  5305. return Math.min(pot, max);
  5306. };
  5307. Tools.GetFilename = function (path) {
  5308. var index = path.lastIndexOf("/");
  5309. if (index < 0)
  5310. return path;
  5311. return path.substring(index + 1);
  5312. };
  5313. Tools.GetDOMTextContent = function (element) {
  5314. var result = "";
  5315. var child = element.firstChild;
  5316. while (child) {
  5317. if (child.nodeType === 3) {
  5318. result += child.textContent;
  5319. }
  5320. child = child.nextSibling;
  5321. }
  5322. return result;
  5323. };
  5324. Tools.ToDegrees = function (angle) {
  5325. return angle * 180 / Math.PI;
  5326. };
  5327. Tools.ToRadians = function (angle) {
  5328. return angle * Math.PI / 180;
  5329. };
  5330. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5331. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5332. var output = "";
  5333. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5334. var i = 0;
  5335. var bytes = new Uint8Array(buffer);
  5336. while (i < bytes.length) {
  5337. chr1 = bytes[i++];
  5338. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5339. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5340. enc1 = chr1 >> 2;
  5341. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5342. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5343. enc4 = chr3 & 63;
  5344. if (isNaN(chr2)) {
  5345. enc3 = enc4 = 64;
  5346. }
  5347. else if (isNaN(chr3)) {
  5348. enc4 = 64;
  5349. }
  5350. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5351. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5352. }
  5353. return "data:image/png;base64," + output;
  5354. };
  5355. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5356. if (bias === void 0) { bias = null; }
  5357. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5358. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5359. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5360. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5361. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5362. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5363. }
  5364. if (bias) {
  5365. minimum.x -= minimum.x * bias.x + bias.y;
  5366. minimum.y -= minimum.y * bias.x + bias.y;
  5367. minimum.z -= minimum.z * bias.x + bias.y;
  5368. maximum.x += maximum.x * bias.x + bias.y;
  5369. maximum.y += maximum.y * bias.x + bias.y;
  5370. maximum.z += maximum.z * bias.x + bias.y;
  5371. }
  5372. return {
  5373. minimum: minimum,
  5374. maximum: maximum
  5375. };
  5376. };
  5377. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5378. if (bias === void 0) { bias = null; }
  5379. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5380. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5381. if (!stride) {
  5382. stride = 3;
  5383. }
  5384. for (var index = start; index < start + count; index++) {
  5385. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5386. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5387. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5388. }
  5389. if (bias) {
  5390. minimum.x -= minimum.x * bias.x + bias.y;
  5391. minimum.y -= minimum.y * bias.x + bias.y;
  5392. minimum.z -= minimum.z * bias.x + bias.y;
  5393. maximum.x += maximum.x * bias.x + bias.y;
  5394. maximum.y += maximum.y * bias.x + bias.y;
  5395. maximum.z += maximum.z * bias.x + bias.y;
  5396. }
  5397. return {
  5398. minimum: minimum,
  5399. maximum: maximum
  5400. };
  5401. };
  5402. Tools.Vector2ArrayFeeder = function (array) {
  5403. return function (index) {
  5404. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5405. var length = isFloatArray ? array.length / 2 : array.length;
  5406. if (index >= length) {
  5407. return null;
  5408. }
  5409. if (isFloatArray) {
  5410. var fa = array;
  5411. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5412. }
  5413. var a = array;
  5414. return a[index];
  5415. };
  5416. };
  5417. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5418. if (bias === void 0) { bias = null; }
  5419. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5420. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5421. var i = 0;
  5422. var cur = feeder(i++);
  5423. while (cur) {
  5424. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5425. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5426. cur = feeder(i++);
  5427. }
  5428. if (bias) {
  5429. minimum.x -= minimum.x * bias.x + bias.y;
  5430. minimum.y -= minimum.y * bias.x + bias.y;
  5431. maximum.x += maximum.x * bias.x + bias.y;
  5432. maximum.y += maximum.y * bias.x + bias.y;
  5433. }
  5434. return {
  5435. minimum: minimum,
  5436. maximum: maximum
  5437. };
  5438. };
  5439. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5440. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5441. return undefined;
  5442. return Array.isArray(obj) ? obj : [obj];
  5443. };
  5444. // Misc.
  5445. Tools.GetPointerPrefix = function () {
  5446. var eventPrefix = "pointer";
  5447. // Check if pointer events are supported
  5448. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5449. eventPrefix = "mouse";
  5450. }
  5451. return eventPrefix;
  5452. };
  5453. /**
  5454. * @param func - the function to be called
  5455. * @param requester - the object that will request the next frame. Falls back to window.
  5456. */
  5457. Tools.QueueNewFrame = function (func, requester) {
  5458. if (requester === void 0) { requester = window; }
  5459. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5460. /*if(requester.isPresenting) {
  5461. return;
  5462. } else*/ if (requester.requestAnimationFrame)
  5463. requester.requestAnimationFrame(func);
  5464. else if (requester.msRequestAnimationFrame)
  5465. requester.msRequestAnimationFrame(func);
  5466. else if (requester.webkitRequestAnimationFrame)
  5467. requester.webkitRequestAnimationFrame(func);
  5468. else if (requester.mozRequestAnimationFrame)
  5469. requester.mozRequestAnimationFrame(func);
  5470. else if (requester.oRequestAnimationFrame)
  5471. requester.oRequestAnimationFrame(func);
  5472. else {
  5473. window.setTimeout(func, 16);
  5474. }
  5475. };
  5476. Tools.RequestFullscreen = function (element) {
  5477. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5478. if (!requestFunction)
  5479. return;
  5480. requestFunction.call(element);
  5481. };
  5482. Tools.ExitFullscreen = function () {
  5483. if (document.exitFullscreen) {
  5484. document.exitFullscreen();
  5485. }
  5486. else if (document.mozCancelFullScreen) {
  5487. document.mozCancelFullScreen();
  5488. }
  5489. else if (document.webkitCancelFullScreen) {
  5490. document.webkitCancelFullScreen();
  5491. }
  5492. else if (document.msCancelFullScreen) {
  5493. document.msCancelFullScreen();
  5494. }
  5495. };
  5496. Tools.SetCorsBehavior = function (url, img) {
  5497. if (Tools.CorsBehavior) {
  5498. switch (typeof (Tools.CorsBehavior)) {
  5499. case "function":
  5500. var result = Tools.CorsBehavior(url);
  5501. if (result) {
  5502. img.crossOrigin = result;
  5503. }
  5504. break;
  5505. case "string":
  5506. default:
  5507. img.crossOrigin = Tools.CorsBehavior;
  5508. break;
  5509. }
  5510. }
  5511. };
  5512. // External files
  5513. Tools.CleanUrl = function (url) {
  5514. url = url.replace(/#/mg, "%23");
  5515. return url;
  5516. };
  5517. Tools.LoadImage = function (url, onload, onerror, database) {
  5518. if (url instanceof ArrayBuffer) {
  5519. url = Tools.EncodeArrayBufferTobase64(url);
  5520. }
  5521. url = Tools.CleanUrl(url);
  5522. var img = new Image();
  5523. if (url.substr(0, 5) !== "data:") {
  5524. Tools.SetCorsBehavior(url, img);
  5525. }
  5526. img.onload = function () {
  5527. onload(img);
  5528. };
  5529. img.onerror = function (err) {
  5530. Tools.Error("Error while trying to load image: " + url);
  5531. if (Tools.UseFallbackTexture) {
  5532. img.src = Tools.fallbackTexture;
  5533. onload(img);
  5534. }
  5535. else {
  5536. onerror();
  5537. }
  5538. };
  5539. var noIndexedDB = function () {
  5540. img.src = url;
  5541. };
  5542. var loadFromIndexedDB = function () {
  5543. database.loadImageFromDB(url, img);
  5544. };
  5545. //ANY database to do!
  5546. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5547. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5548. }
  5549. else {
  5550. if (url.indexOf("file:") !== 0) {
  5551. noIndexedDB();
  5552. }
  5553. else {
  5554. var textureName = url.substring(5).toLowerCase();
  5555. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5556. try {
  5557. var blobURL;
  5558. try {
  5559. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5560. }
  5561. catch (ex) {
  5562. // Chrome doesn't support oneTimeOnly parameter
  5563. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5564. }
  5565. img.src = blobURL;
  5566. }
  5567. catch (e) {
  5568. img.src = null;
  5569. }
  5570. }
  5571. else {
  5572. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5573. img.src = Tools.fallbackTexture;
  5574. }
  5575. }
  5576. }
  5577. return img;
  5578. };
  5579. //ANY
  5580. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5581. url = Tools.CleanUrl(url);
  5582. var noIndexedDB = function () {
  5583. var request = new XMLHttpRequest();
  5584. var loadUrl = Tools.BaseUrl + url;
  5585. request.open('GET', loadUrl, true);
  5586. if (useArrayBuffer) {
  5587. request.responseType = "arraybuffer";
  5588. }
  5589. request.onprogress = progressCallBack;
  5590. request.onreadystatechange = function () {
  5591. // In case of undefined state in some browsers.
  5592. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5593. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5594. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5595. callback(!useArrayBuffer ? request.responseText : request.response);
  5596. }
  5597. else {
  5598. if (onError) {
  5599. onError(request);
  5600. }
  5601. else {
  5602. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5603. }
  5604. }
  5605. }
  5606. };
  5607. request.send(null);
  5608. };
  5609. var loadFromIndexedDB = function () {
  5610. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5611. };
  5612. if (url.indexOf("file:") !== -1) {
  5613. var fileName = url.substring(5).toLowerCase();
  5614. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5615. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5616. }
  5617. else {
  5618. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5619. }
  5620. }
  5621. else {
  5622. // Caching all files
  5623. if (database && database.enableSceneOffline) {
  5624. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5625. }
  5626. else {
  5627. noIndexedDB();
  5628. }
  5629. }
  5630. };
  5631. /**
  5632. * Load a script (identified by an url). When the url returns, the
  5633. * content of this file is added into a new script element, attached to the DOM (body element)
  5634. */
  5635. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5636. var head = document.getElementsByTagName('head')[0];
  5637. var script = document.createElement('script');
  5638. script.type = 'text/javascript';
  5639. script.src = scriptUrl;
  5640. var self = this;
  5641. script.onload = function () {
  5642. if (onSuccess) {
  5643. onSuccess();
  5644. }
  5645. };
  5646. script.onerror = function () {
  5647. if (onError) {
  5648. onError();
  5649. }
  5650. };
  5651. head.appendChild(script);
  5652. };
  5653. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5654. var reader = new FileReader();
  5655. reader.onload = function (e) {
  5656. //target doesn't have result from ts 1.3
  5657. callback(e.target['result']);
  5658. };
  5659. reader.onprogress = progressCallback;
  5660. reader.readAsDataURL(fileToLoad);
  5661. };
  5662. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5663. var reader = new FileReader();
  5664. reader.onerror = function (e) {
  5665. Tools.Log("Error while reading file: " + fileToLoad.name);
  5666. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5667. };
  5668. reader.onload = function (e) {
  5669. //target doesn't have result from ts 1.3
  5670. callback(e.target['result']);
  5671. };
  5672. reader.onprogress = progressCallBack;
  5673. if (!useArrayBuffer) {
  5674. // Asynchronous read
  5675. reader.readAsText(fileToLoad);
  5676. }
  5677. else {
  5678. reader.readAsArrayBuffer(fileToLoad);
  5679. }
  5680. };
  5681. //returns a downloadable url to a file content.
  5682. Tools.FileAsURL = function (content) {
  5683. var fileBlob = new Blob([content]);
  5684. var url = window.URL || window.webkitURL;
  5685. var link = url.createObjectURL(fileBlob);
  5686. return link;
  5687. };
  5688. // Misc.
  5689. Tools.Format = function (value, decimals) {
  5690. if (decimals === void 0) { decimals = 2; }
  5691. return value.toFixed(decimals);
  5692. };
  5693. Tools.CheckExtends = function (v, min, max) {
  5694. if (v.x < min.x)
  5695. min.x = v.x;
  5696. if (v.y < min.y)
  5697. min.y = v.y;
  5698. if (v.z < min.z)
  5699. min.z = v.z;
  5700. if (v.x > max.x)
  5701. max.x = v.x;
  5702. if (v.y > max.y)
  5703. max.y = v.y;
  5704. if (v.z > max.z)
  5705. max.z = v.z;
  5706. };
  5707. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5708. for (var prop in source) {
  5709. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5710. continue;
  5711. }
  5712. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5713. continue;
  5714. }
  5715. var sourceValue = source[prop];
  5716. var typeOfSourceValue = typeof sourceValue;
  5717. if (typeOfSourceValue === "function") {
  5718. continue;
  5719. }
  5720. if (typeOfSourceValue === "object") {
  5721. if (sourceValue instanceof Array) {
  5722. destination[prop] = [];
  5723. if (sourceValue.length > 0) {
  5724. if (typeof sourceValue[0] == "object") {
  5725. for (var index = 0; index < sourceValue.length; index++) {
  5726. var clonedValue = cloneValue(sourceValue[index], destination);
  5727. if (destination[prop].indexOf(clonedValue) === -1) {
  5728. destination[prop].push(clonedValue);
  5729. }
  5730. }
  5731. }
  5732. else {
  5733. destination[prop] = sourceValue.slice(0);
  5734. }
  5735. }
  5736. }
  5737. else {
  5738. destination[prop] = cloneValue(sourceValue, destination);
  5739. }
  5740. }
  5741. else {
  5742. destination[prop] = sourceValue;
  5743. }
  5744. }
  5745. };
  5746. Tools.IsEmpty = function (obj) {
  5747. for (var i in obj) {
  5748. return false;
  5749. }
  5750. return true;
  5751. };
  5752. Tools.RegisterTopRootEvents = function (events) {
  5753. for (var index = 0; index < events.length; index++) {
  5754. var event = events[index];
  5755. window.addEventListener(event.name, event.handler, false);
  5756. try {
  5757. if (window.parent) {
  5758. window.parent.addEventListener(event.name, event.handler, false);
  5759. }
  5760. }
  5761. catch (e) {
  5762. // Silently fails...
  5763. }
  5764. }
  5765. };
  5766. Tools.UnregisterTopRootEvents = function (events) {
  5767. for (var index = 0; index < events.length; index++) {
  5768. var event = events[index];
  5769. window.removeEventListener(event.name, event.handler);
  5770. try {
  5771. if (window.parent) {
  5772. window.parent.removeEventListener(event.name, event.handler);
  5773. }
  5774. }
  5775. catch (e) {
  5776. // Silently fails...
  5777. }
  5778. }
  5779. };
  5780. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5781. if (mimeType === void 0) { mimeType = "image/png"; }
  5782. // Read the contents of the framebuffer
  5783. var numberOfChannelsByLine = width * 4;
  5784. var halfHeight = height / 2;
  5785. //Reading datas from WebGL
  5786. var data = engine.readPixels(0, 0, width, height);
  5787. //To flip image on Y axis.
  5788. for (var i = 0; i < halfHeight; i++) {
  5789. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5790. var currentCell = j + i * numberOfChannelsByLine;
  5791. var targetLine = height - i - 1;
  5792. var targetCell = j + targetLine * numberOfChannelsByLine;
  5793. var temp = data[currentCell];
  5794. data[currentCell] = data[targetCell];
  5795. data[targetCell] = temp;
  5796. }
  5797. }
  5798. // Create a 2D canvas to store the result
  5799. if (!screenshotCanvas) {
  5800. screenshotCanvas = document.createElement('canvas');
  5801. }
  5802. screenshotCanvas.width = width;
  5803. screenshotCanvas.height = height;
  5804. var context = screenshotCanvas.getContext('2d');
  5805. // Copy the pixels to a 2D canvas
  5806. var imageData = context.createImageData(width, height);
  5807. var castData = (imageData.data);
  5808. castData.set(data);
  5809. context.putImageData(imageData, 0, 0);
  5810. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5811. };
  5812. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5813. if (mimeType === void 0) { mimeType = "image/png"; }
  5814. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5815. if (successCallback) {
  5816. successCallback(base64Image);
  5817. }
  5818. else {
  5819. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5820. if (("download" in document.createElement("a"))) {
  5821. var a = window.document.createElement("a");
  5822. a.href = base64Image;
  5823. var date = new Date();
  5824. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5825. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5826. window.document.body.appendChild(a);
  5827. a.addEventListener("click", function () {
  5828. a.parentElement.removeChild(a);
  5829. });
  5830. a.click();
  5831. //Or opening a new tab with the image if it is not possible to automatically start download.
  5832. }
  5833. else {
  5834. var newWindow = window.open("");
  5835. var img = newWindow.document.createElement("img");
  5836. img.src = base64Image;
  5837. newWindow.document.body.appendChild(img);
  5838. }
  5839. }
  5840. };
  5841. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5842. if (mimeType === void 0) { mimeType = "image/png"; }
  5843. var width;
  5844. var height;
  5845. // If a precision value is specified
  5846. if (size.precision) {
  5847. width = Math.round(engine.getRenderWidth() * size.precision);
  5848. height = Math.round(width / engine.getAspectRatio(camera));
  5849. }
  5850. else if (size.width && size.height) {
  5851. width = size.width;
  5852. height = size.height;
  5853. }
  5854. else if (size.width && !size.height) {
  5855. width = size.width;
  5856. height = Math.round(width / engine.getAspectRatio(camera));
  5857. }
  5858. else if (size.height && !size.width) {
  5859. height = size.height;
  5860. width = Math.round(height * engine.getAspectRatio(camera));
  5861. }
  5862. else if (!isNaN(size)) {
  5863. height = size;
  5864. width = size;
  5865. }
  5866. else {
  5867. Tools.Error("Invalid 'size' parameter !");
  5868. return;
  5869. }
  5870. if (!screenshotCanvas) {
  5871. screenshotCanvas = document.createElement('canvas');
  5872. }
  5873. screenshotCanvas.width = width;
  5874. screenshotCanvas.height = height;
  5875. var renderContext = screenshotCanvas.getContext("2d");
  5876. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5877. var newWidth = width;
  5878. var newHeight = newWidth / ratio;
  5879. if (newHeight > height) {
  5880. newHeight = height;
  5881. newWidth = newHeight * ratio;
  5882. }
  5883. var offsetX = Math.max(0, width - newWidth) / 2;
  5884. var offsetY = Math.max(0, height - newHeight) / 2;
  5885. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5886. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5887. };
  5888. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5889. if (mimeType === void 0) { mimeType = "image/png"; }
  5890. if (samples === void 0) { samples = 1; }
  5891. var width;
  5892. var height;
  5893. //If a precision value is specified
  5894. if (size.precision) {
  5895. width = Math.round(engine.getRenderWidth() * size.precision);
  5896. height = Math.round(width / engine.getAspectRatio(camera));
  5897. size = { width: width, height: height };
  5898. }
  5899. else if (size.width && size.height) {
  5900. width = size.width;
  5901. height = size.height;
  5902. }
  5903. else if (size.width && !size.height) {
  5904. width = size.width;
  5905. height = Math.round(width / engine.getAspectRatio(camera));
  5906. size = { width: width, height: height };
  5907. }
  5908. else if (size.height && !size.width) {
  5909. height = size.height;
  5910. width = Math.round(height * engine.getAspectRatio(camera));
  5911. size = { width: width, height: height };
  5912. }
  5913. else if (!isNaN(size)) {
  5914. height = size;
  5915. width = size;
  5916. }
  5917. else {
  5918. Tools.Error("Invalid 'size' parameter !");
  5919. return;
  5920. }
  5921. var scene = camera.getScene();
  5922. var previousCamera = null;
  5923. if (scene.activeCamera !== camera) {
  5924. previousCamera = scene.activeCamera;
  5925. scene.activeCamera = camera;
  5926. }
  5927. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5928. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5929. texture.renderList = scene.meshes;
  5930. texture.samples = samples;
  5931. texture.onAfterRenderObservable.add(function () {
  5932. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5933. });
  5934. scene.incrementRenderId();
  5935. scene.resetCachedMaterial();
  5936. texture.render(true);
  5937. texture.dispose();
  5938. if (previousCamera) {
  5939. scene.activeCamera = previousCamera;
  5940. }
  5941. camera.getProjectionMatrix(true); // Force cache refresh;
  5942. };
  5943. // XHR response validator for local file scenario
  5944. Tools.ValidateXHRData = function (xhr, dataType) {
  5945. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5946. if (dataType === void 0) { dataType = 7; }
  5947. try {
  5948. if (dataType & 1) {
  5949. if (xhr.responseText && xhr.responseText.length > 0) {
  5950. return true;
  5951. }
  5952. else if (dataType === 1) {
  5953. return false;
  5954. }
  5955. }
  5956. if (dataType & 2) {
  5957. // Check header width and height since there is no "TGA" magic number
  5958. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5959. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5960. return true;
  5961. }
  5962. else if (dataType === 2) {
  5963. return false;
  5964. }
  5965. }
  5966. if (dataType & 4) {
  5967. // Check for the "DDS" magic number
  5968. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5969. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5970. return true;
  5971. }
  5972. else {
  5973. return false;
  5974. }
  5975. }
  5976. }
  5977. catch (e) {
  5978. // Global protection
  5979. }
  5980. return false;
  5981. };
  5982. /**
  5983. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5984. * Be aware Math.random() could cause collisions, but:
  5985. * "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"
  5986. */
  5987. Tools.RandomId = function () {
  5988. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5989. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5990. return v.toString(16);
  5991. });
  5992. };
  5993. Object.defineProperty(Tools, "NoneLogLevel", {
  5994. get: function () {
  5995. return Tools._NoneLogLevel;
  5996. },
  5997. enumerable: true,
  5998. configurable: true
  5999. });
  6000. Object.defineProperty(Tools, "MessageLogLevel", {
  6001. get: function () {
  6002. return Tools._MessageLogLevel;
  6003. },
  6004. enumerable: true,
  6005. configurable: true
  6006. });
  6007. Object.defineProperty(Tools, "WarningLogLevel", {
  6008. get: function () {
  6009. return Tools._WarningLogLevel;
  6010. },
  6011. enumerable: true,
  6012. configurable: true
  6013. });
  6014. Object.defineProperty(Tools, "ErrorLogLevel", {
  6015. get: function () {
  6016. return Tools._ErrorLogLevel;
  6017. },
  6018. enumerable: true,
  6019. configurable: true
  6020. });
  6021. Object.defineProperty(Tools, "AllLogLevel", {
  6022. get: function () {
  6023. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6024. },
  6025. enumerable: true,
  6026. configurable: true
  6027. });
  6028. Tools._AddLogEntry = function (entry) {
  6029. Tools._LogCache = entry + Tools._LogCache;
  6030. if (Tools.OnNewCacheEntry) {
  6031. Tools.OnNewCacheEntry(entry);
  6032. }
  6033. };
  6034. Tools._FormatMessage = function (message) {
  6035. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6036. var date = new Date();
  6037. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6038. };
  6039. Tools._LogDisabled = function (message) {
  6040. // nothing to do
  6041. };
  6042. Tools._LogEnabled = function (message) {
  6043. var formattedMessage = Tools._FormatMessage(message);
  6044. console.log("BJS - " + formattedMessage);
  6045. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6046. Tools._AddLogEntry(entry);
  6047. };
  6048. Tools._WarnDisabled = function (message) {
  6049. // nothing to do
  6050. };
  6051. Tools._WarnEnabled = function (message) {
  6052. var formattedMessage = Tools._FormatMessage(message);
  6053. console.warn("BJS - " + formattedMessage);
  6054. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6055. Tools._AddLogEntry(entry);
  6056. };
  6057. Tools._ErrorDisabled = function (message) {
  6058. // nothing to do
  6059. };
  6060. Tools._ErrorEnabled = function (message) {
  6061. Tools.errorsCount++;
  6062. var formattedMessage = Tools._FormatMessage(message);
  6063. console.error("BJS - " + formattedMessage);
  6064. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6065. Tools._AddLogEntry(entry);
  6066. };
  6067. Object.defineProperty(Tools, "LogCache", {
  6068. get: function () {
  6069. return Tools._LogCache;
  6070. },
  6071. enumerable: true,
  6072. configurable: true
  6073. });
  6074. Tools.ClearLogCache = function () {
  6075. Tools._LogCache = "";
  6076. Tools.errorsCount = 0;
  6077. };
  6078. Object.defineProperty(Tools, "LogLevels", {
  6079. set: function (level) {
  6080. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6081. Tools.Log = Tools._LogEnabled;
  6082. }
  6083. else {
  6084. Tools.Log = Tools._LogDisabled;
  6085. }
  6086. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6087. Tools.Warn = Tools._WarnEnabled;
  6088. }
  6089. else {
  6090. Tools.Warn = Tools._WarnDisabled;
  6091. }
  6092. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6093. Tools.Error = Tools._ErrorEnabled;
  6094. }
  6095. else {
  6096. Tools.Error = Tools._ErrorDisabled;
  6097. }
  6098. },
  6099. enumerable: true,
  6100. configurable: true
  6101. });
  6102. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6103. get: function () {
  6104. return Tools._PerformanceNoneLogLevel;
  6105. },
  6106. enumerable: true,
  6107. configurable: true
  6108. });
  6109. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6110. get: function () {
  6111. return Tools._PerformanceUserMarkLogLevel;
  6112. },
  6113. enumerable: true,
  6114. configurable: true
  6115. });
  6116. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6117. get: function () {
  6118. return Tools._PerformanceConsoleLogLevel;
  6119. },
  6120. enumerable: true,
  6121. configurable: true
  6122. });
  6123. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6124. set: function (level) {
  6125. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6126. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6127. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6128. return;
  6129. }
  6130. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6131. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6132. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6133. return;
  6134. }
  6135. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6136. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6137. },
  6138. enumerable: true,
  6139. configurable: true
  6140. });
  6141. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6142. };
  6143. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6144. };
  6145. Tools._StartUserMark = function (counterName, condition) {
  6146. if (condition === void 0) { condition = true; }
  6147. if (!condition || !Tools._performance.mark) {
  6148. return;
  6149. }
  6150. Tools._performance.mark(counterName + "-Begin");
  6151. };
  6152. Tools._EndUserMark = function (counterName, condition) {
  6153. if (condition === void 0) { condition = true; }
  6154. if (!condition || !Tools._performance.mark) {
  6155. return;
  6156. }
  6157. Tools._performance.mark(counterName + "-End");
  6158. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6159. };
  6160. Tools._StartPerformanceConsole = function (counterName, condition) {
  6161. if (condition === void 0) { condition = true; }
  6162. if (!condition) {
  6163. return;
  6164. }
  6165. Tools._StartUserMark(counterName, condition);
  6166. if (console.time) {
  6167. console.time(counterName);
  6168. }
  6169. };
  6170. Tools._EndPerformanceConsole = function (counterName, condition) {
  6171. if (condition === void 0) { condition = true; }
  6172. if (!condition) {
  6173. return;
  6174. }
  6175. Tools._EndUserMark(counterName, condition);
  6176. if (console.time) {
  6177. console.timeEnd(counterName);
  6178. }
  6179. };
  6180. Object.defineProperty(Tools, "Now", {
  6181. get: function () {
  6182. if (window.performance && window.performance.now) {
  6183. return window.performance.now();
  6184. }
  6185. return new Date().getTime();
  6186. },
  6187. enumerable: true,
  6188. configurable: true
  6189. });
  6190. /**
  6191. * This method will return the name of the class used to create the instance of the given object.
  6192. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6193. * @param object the object to get the class name from
  6194. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6195. */
  6196. Tools.getClassName = function (object, isType) {
  6197. if (isType === void 0) { isType = false; }
  6198. var name = null;
  6199. if (!isType && object.getClassName) {
  6200. name = object.getClassName();
  6201. }
  6202. else {
  6203. if (object instanceof Object) {
  6204. var classObj = isType ? object : Object.getPrototypeOf(object);
  6205. name = classObj.constructor["__bjsclassName__"];
  6206. }
  6207. if (!name) {
  6208. name = typeof object;
  6209. }
  6210. }
  6211. return name;
  6212. };
  6213. Tools.first = function (array, predicate) {
  6214. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6215. var el = array_1[_i];
  6216. if (predicate(el)) {
  6217. return el;
  6218. }
  6219. }
  6220. };
  6221. /**
  6222. * This method will return the name of the full name of the class, including its owning module (if any).
  6223. * 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).
  6224. * @param object the object to get the class name from
  6225. * @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.
  6226. */
  6227. Tools.getFullClassName = function (object, isType) {
  6228. if (isType === void 0) { isType = false; }
  6229. var className = null;
  6230. var moduleName = null;
  6231. if (!isType && object.getClassName) {
  6232. className = object.getClassName();
  6233. }
  6234. else {
  6235. if (object instanceof Object) {
  6236. var classObj = isType ? object : Object.getPrototypeOf(object);
  6237. className = classObj.constructor["__bjsclassName__"];
  6238. moduleName = classObj.constructor["__bjsmoduleName__"];
  6239. }
  6240. if (!className) {
  6241. className = typeof object;
  6242. }
  6243. }
  6244. if (!className) {
  6245. return null;
  6246. }
  6247. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6248. };
  6249. /**
  6250. * 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.
  6251. * @param array
  6252. */
  6253. Tools.arrayOrStringFeeder = function (array) {
  6254. return function (index) {
  6255. if (index >= array.length) {
  6256. return null;
  6257. }
  6258. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6259. if (val && val.getHashCode) {
  6260. val = val.getHashCode();
  6261. }
  6262. if (typeof val === "string") {
  6263. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6264. }
  6265. return val;
  6266. };
  6267. };
  6268. /**
  6269. * Compute the hashCode of a stream of number
  6270. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6271. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6272. * @return the hash code computed
  6273. */
  6274. Tools.hashCodeFromStream = function (feeder) {
  6275. // Based from here: http://stackoverflow.com/a/7616484/802124
  6276. var hash = 0;
  6277. var index = 0;
  6278. var chr = feeder(index++);
  6279. while (chr != null) {
  6280. hash = ((hash << 5) - hash) + chr;
  6281. hash |= 0; // Convert to 32bit integer
  6282. chr = feeder(index++);
  6283. }
  6284. return hash;
  6285. };
  6286. return Tools;
  6287. }());
  6288. Tools.BaseUrl = "";
  6289. Tools.CorsBehavior = "anonymous";
  6290. Tools.UseFallbackTexture = true;
  6291. // Used in case of a texture loading problem
  6292. 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";
  6293. // Logs
  6294. Tools._NoneLogLevel = 0;
  6295. Tools._MessageLogLevel = 1;
  6296. Tools._WarningLogLevel = 2;
  6297. Tools._ErrorLogLevel = 4;
  6298. Tools._LogCache = "";
  6299. Tools.errorsCount = 0;
  6300. Tools.Log = Tools._LogEnabled;
  6301. Tools.Warn = Tools._WarnEnabled;
  6302. Tools.Error = Tools._ErrorEnabled;
  6303. // Performances
  6304. Tools._PerformanceNoneLogLevel = 0;
  6305. Tools._PerformanceUserMarkLogLevel = 1;
  6306. Tools._PerformanceConsoleLogLevel = 2;
  6307. Tools._performance = window.performance;
  6308. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6309. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6310. BABYLON.Tools = Tools;
  6311. /**
  6312. * This class is used to track a performance counter which is number based.
  6313. * The user has access to many properties which give statistics of different nature
  6314. *
  6315. * The implementer can track two kinds of Performance Counter: time and count
  6316. * 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.
  6317. * 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.
  6318. */
  6319. var PerfCounter = (function () {
  6320. function PerfCounter() {
  6321. this._startMonitoringTime = 0;
  6322. this._min = 0;
  6323. this._max = 0;
  6324. this._average = 0;
  6325. this._lastSecAverage = 0;
  6326. this._current = 0;
  6327. this._totalValueCount = 0;
  6328. this._totalAccumulated = 0;
  6329. this._lastSecAccumulated = 0;
  6330. this._lastSecTime = 0;
  6331. this._lastSecValueCount = 0;
  6332. }
  6333. Object.defineProperty(PerfCounter.prototype, "min", {
  6334. /**
  6335. * Returns the smallest value ever
  6336. */
  6337. get: function () {
  6338. return this._min;
  6339. },
  6340. enumerable: true,
  6341. configurable: true
  6342. });
  6343. Object.defineProperty(PerfCounter.prototype, "max", {
  6344. /**
  6345. * Returns the biggest value ever
  6346. */
  6347. get: function () {
  6348. return this._max;
  6349. },
  6350. enumerable: true,
  6351. configurable: true
  6352. });
  6353. Object.defineProperty(PerfCounter.prototype, "average", {
  6354. /**
  6355. * Returns the average value since the performance counter is running
  6356. */
  6357. get: function () {
  6358. return this._average;
  6359. },
  6360. enumerable: true,
  6361. configurable: true
  6362. });
  6363. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6364. /**
  6365. * Returns the average value of the last second the counter was monitored
  6366. */
  6367. get: function () {
  6368. return this._lastSecAverage;
  6369. },
  6370. enumerable: true,
  6371. configurable: true
  6372. });
  6373. Object.defineProperty(PerfCounter.prototype, "current", {
  6374. /**
  6375. * Returns the current value
  6376. */
  6377. get: function () {
  6378. return this._current;
  6379. },
  6380. enumerable: true,
  6381. configurable: true
  6382. });
  6383. Object.defineProperty(PerfCounter.prototype, "total", {
  6384. get: function () {
  6385. return this._totalAccumulated;
  6386. },
  6387. enumerable: true,
  6388. configurable: true
  6389. });
  6390. /**
  6391. * Call this method to start monitoring a new frame.
  6392. * 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.
  6393. */
  6394. PerfCounter.prototype.fetchNewFrame = function () {
  6395. this._totalValueCount++;
  6396. this._current = 0;
  6397. this._lastSecValueCount++;
  6398. };
  6399. /**
  6400. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6401. * @param newCount the count value to add to the monitored count
  6402. * @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.
  6403. */
  6404. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6405. if (!PerfCounter.Enabled) {
  6406. return;
  6407. }
  6408. this._current += newCount;
  6409. if (fetchResult) {
  6410. this._fetchResult();
  6411. }
  6412. };
  6413. /**
  6414. * Start monitoring this performance counter
  6415. */
  6416. PerfCounter.prototype.beginMonitoring = function () {
  6417. if (!PerfCounter.Enabled) {
  6418. return;
  6419. }
  6420. this._startMonitoringTime = Tools.Now;
  6421. };
  6422. /**
  6423. * Compute the time lapsed since the previous beginMonitoring() call.
  6424. * @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
  6425. */
  6426. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6427. if (newFrame === void 0) { newFrame = true; }
  6428. if (!PerfCounter.Enabled) {
  6429. return;
  6430. }
  6431. if (newFrame) {
  6432. this.fetchNewFrame();
  6433. }
  6434. var currentTime = Tools.Now;
  6435. this._current = currentTime - this._startMonitoringTime;
  6436. if (newFrame) {
  6437. this._fetchResult();
  6438. }
  6439. };
  6440. PerfCounter.prototype._fetchResult = function () {
  6441. this._totalAccumulated += this._current;
  6442. this._lastSecAccumulated += this._current;
  6443. // Min/Max update
  6444. this._min = Math.min(this._min, this._current);
  6445. this._max = Math.max(this._max, this._current);
  6446. this._average = this._totalAccumulated / this._totalValueCount;
  6447. // Reset last sec?
  6448. var now = Tools.Now;
  6449. if ((now - this._lastSecTime) > 1000) {
  6450. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6451. this._lastSecTime = now;
  6452. this._lastSecAccumulated = 0;
  6453. this._lastSecValueCount = 0;
  6454. }
  6455. };
  6456. return PerfCounter;
  6457. }());
  6458. PerfCounter.Enabled = true;
  6459. BABYLON.PerfCounter = PerfCounter;
  6460. /**
  6461. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6462. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6463. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6464. * @param name The name of the class, case should be preserved
  6465. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6466. */
  6467. function className(name, module) {
  6468. return function (target) {
  6469. target["__bjsclassName__"] = name;
  6470. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6471. };
  6472. }
  6473. BABYLON.className = className;
  6474. /**
  6475. * An implementation of a loop for asynchronous functions.
  6476. */
  6477. var AsyncLoop = (function () {
  6478. /**
  6479. * Constroctor.
  6480. * @param iterations the number of iterations.
  6481. * @param _fn the function to run each iteration
  6482. * @param _successCallback the callback that will be called upon succesful execution
  6483. * @param offset starting offset.
  6484. */
  6485. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6486. if (offset === void 0) { offset = 0; }
  6487. this.iterations = iterations;
  6488. this._fn = _fn;
  6489. this._successCallback = _successCallback;
  6490. this.index = offset - 1;
  6491. this._done = false;
  6492. }
  6493. /**
  6494. * Execute the next iteration. Must be called after the last iteration was finished.
  6495. */
  6496. AsyncLoop.prototype.executeNext = function () {
  6497. if (!this._done) {
  6498. if (this.index + 1 < this.iterations) {
  6499. ++this.index;
  6500. this._fn(this);
  6501. }
  6502. else {
  6503. this.breakLoop();
  6504. }
  6505. }
  6506. };
  6507. /**
  6508. * Break the loop and run the success callback.
  6509. */
  6510. AsyncLoop.prototype.breakLoop = function () {
  6511. this._done = true;
  6512. this._successCallback();
  6513. };
  6514. /**
  6515. * Helper function
  6516. */
  6517. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6518. if (offset === void 0) { offset = 0; }
  6519. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6520. loop.executeNext();
  6521. return loop;
  6522. };
  6523. /**
  6524. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6525. * @param iterations total number of iterations
  6526. * @param syncedIterations number of synchronous iterations in each async iteration.
  6527. * @param fn the function to call each iteration.
  6528. * @param callback a success call back that will be called when iterating stops.
  6529. * @param breakFunction a break condition (optional)
  6530. * @param timeout timeout settings for the setTimeout function. default - 0.
  6531. * @constructor
  6532. */
  6533. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6534. if (timeout === void 0) { timeout = 0; }
  6535. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6536. if (breakFunction && breakFunction())
  6537. loop.breakLoop();
  6538. else {
  6539. setTimeout(function () {
  6540. for (var i = 0; i < syncedIterations; ++i) {
  6541. var iteration = (loop.index * syncedIterations) + i;
  6542. if (iteration >= iterations)
  6543. break;
  6544. fn(iteration);
  6545. if (breakFunction && breakFunction()) {
  6546. loop.breakLoop();
  6547. break;
  6548. }
  6549. }
  6550. loop.executeNext();
  6551. }, timeout);
  6552. }
  6553. }, callback);
  6554. };
  6555. return AsyncLoop;
  6556. }());
  6557. BABYLON.AsyncLoop = AsyncLoop;
  6558. })(BABYLON || (BABYLON = {}));
  6559. //# sourceMappingURL=babylon.tools.js.map
  6560. var BABYLON;
  6561. (function (BABYLON) {
  6562. var Internals;
  6563. (function (Internals) {
  6564. var _AlphaState = (function () {
  6565. /**
  6566. * Initializes the state.
  6567. */
  6568. function _AlphaState() {
  6569. this._isAlphaBlendDirty = false;
  6570. this._isBlendFunctionParametersDirty = false;
  6571. this._isBlendEquationParametersDirty = false;
  6572. this._isBlendConstantsDirty = false;
  6573. this._alphaBlend = false;
  6574. this._blendFunctionParameters = new Array(4);
  6575. this._blendEquationParameters = new Array(2);
  6576. this._blendConstants = new Array(4);
  6577. this.reset();
  6578. }
  6579. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6580. get: function () {
  6581. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6582. },
  6583. enumerable: true,
  6584. configurable: true
  6585. });
  6586. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6587. get: function () {
  6588. return this._alphaBlend;
  6589. },
  6590. set: function (value) {
  6591. if (this._alphaBlend === value) {
  6592. return;
  6593. }
  6594. this._alphaBlend = value;
  6595. this._isAlphaBlendDirty = true;
  6596. },
  6597. enumerable: true,
  6598. configurable: true
  6599. });
  6600. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6601. if (this._blendConstants[0] === r &&
  6602. this._blendConstants[1] === g &&
  6603. this._blendConstants[2] === b &&
  6604. this._blendConstants[3] === a) {
  6605. return;
  6606. }
  6607. this._blendConstants[0] = r;
  6608. this._blendConstants[1] = g;
  6609. this._blendConstants[2] = b;
  6610. this._blendConstants[3] = a;
  6611. this._isBlendConstantsDirty = true;
  6612. };
  6613. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6614. if (this._blendFunctionParameters[0] === value0 &&
  6615. this._blendFunctionParameters[1] === value1 &&
  6616. this._blendFunctionParameters[2] === value2 &&
  6617. this._blendFunctionParameters[3] === value3) {
  6618. return;
  6619. }
  6620. this._blendFunctionParameters[0] = value0;
  6621. this._blendFunctionParameters[1] = value1;
  6622. this._blendFunctionParameters[2] = value2;
  6623. this._blendFunctionParameters[3] = value3;
  6624. this._isBlendFunctionParametersDirty = true;
  6625. };
  6626. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6627. if (this._blendEquationParameters[0] === rgb &&
  6628. this._blendEquationParameters[1] === alpha) {
  6629. return;
  6630. }
  6631. this._blendEquationParameters[0] = rgb;
  6632. this._blendEquationParameters[1] = alpha;
  6633. this._isBlendEquationParametersDirty = true;
  6634. };
  6635. _AlphaState.prototype.reset = function () {
  6636. this._alphaBlend = false;
  6637. this._blendFunctionParameters[0] = null;
  6638. this._blendFunctionParameters[1] = null;
  6639. this._blendFunctionParameters[2] = null;
  6640. this._blendFunctionParameters[3] = null;
  6641. this._blendEquationParameters[0] = null;
  6642. this._blendEquationParameters[1] = null;
  6643. this._blendConstants[0] = null;
  6644. this._blendConstants[1] = null;
  6645. this._blendConstants[2] = null;
  6646. this._blendConstants[3] = null;
  6647. this._isAlphaBlendDirty = true;
  6648. this._isBlendFunctionParametersDirty = false;
  6649. this._isBlendEquationParametersDirty = false;
  6650. this._isBlendConstantsDirty = false;
  6651. };
  6652. _AlphaState.prototype.apply = function (gl) {
  6653. if (!this.isDirty) {
  6654. return;
  6655. }
  6656. // Alpha blend
  6657. if (this._isAlphaBlendDirty) {
  6658. if (this._alphaBlend) {
  6659. gl.enable(gl.BLEND);
  6660. }
  6661. else {
  6662. gl.disable(gl.BLEND);
  6663. }
  6664. this._isAlphaBlendDirty = false;
  6665. }
  6666. // Alpha function
  6667. if (this._isBlendFunctionParametersDirty) {
  6668. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6669. this._isBlendFunctionParametersDirty = false;
  6670. }
  6671. // Alpha equation
  6672. if (this._isBlendEquationParametersDirty) {
  6673. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6674. this._isBlendEquationParametersDirty = false;
  6675. }
  6676. // Constants
  6677. if (this._isBlendConstantsDirty) {
  6678. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6679. this._isBlendConstantsDirty = false;
  6680. }
  6681. };
  6682. return _AlphaState;
  6683. }());
  6684. Internals._AlphaState = _AlphaState;
  6685. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6686. })(BABYLON || (BABYLON = {}));
  6687. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6688. var BABYLON;
  6689. (function (BABYLON) {
  6690. var Internals;
  6691. (function (Internals) {
  6692. var _DepthCullingState = (function () {
  6693. /**
  6694. * Initializes the state.
  6695. */
  6696. function _DepthCullingState() {
  6697. this._isDepthTestDirty = false;
  6698. this._isDepthMaskDirty = false;
  6699. this._isDepthFuncDirty = false;
  6700. this._isCullFaceDirty = false;
  6701. this._isCullDirty = false;
  6702. this._isZOffsetDirty = false;
  6703. this.reset();
  6704. }
  6705. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6706. get: function () {
  6707. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6708. },
  6709. enumerable: true,
  6710. configurable: true
  6711. });
  6712. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6713. get: function () {
  6714. return this._zOffset;
  6715. },
  6716. set: function (value) {
  6717. if (this._zOffset === value) {
  6718. return;
  6719. }
  6720. this._zOffset = value;
  6721. this._isZOffsetDirty = true;
  6722. },
  6723. enumerable: true,
  6724. configurable: true
  6725. });
  6726. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6727. get: function () {
  6728. return this._cullFace;
  6729. },
  6730. set: function (value) {
  6731. if (this._cullFace === value) {
  6732. return;
  6733. }
  6734. this._cullFace = value;
  6735. this._isCullFaceDirty = true;
  6736. },
  6737. enumerable: true,
  6738. configurable: true
  6739. });
  6740. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6741. get: function () {
  6742. return this._cull;
  6743. },
  6744. set: function (value) {
  6745. if (this._cull === value) {
  6746. return;
  6747. }
  6748. this._cull = value;
  6749. this._isCullDirty = true;
  6750. },
  6751. enumerable: true,
  6752. configurable: true
  6753. });
  6754. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6755. get: function () {
  6756. return this._depthFunc;
  6757. },
  6758. set: function (value) {
  6759. if (this._depthFunc === value) {
  6760. return;
  6761. }
  6762. this._depthFunc = value;
  6763. this._isDepthFuncDirty = true;
  6764. },
  6765. enumerable: true,
  6766. configurable: true
  6767. });
  6768. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6769. get: function () {
  6770. return this._depthMask;
  6771. },
  6772. set: function (value) {
  6773. if (this._depthMask === value) {
  6774. return;
  6775. }
  6776. this._depthMask = value;
  6777. this._isDepthMaskDirty = true;
  6778. },
  6779. enumerable: true,
  6780. configurable: true
  6781. });
  6782. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6783. get: function () {
  6784. return this._depthTest;
  6785. },
  6786. set: function (value) {
  6787. if (this._depthTest === value) {
  6788. return;
  6789. }
  6790. this._depthTest = value;
  6791. this._isDepthTestDirty = true;
  6792. },
  6793. enumerable: true,
  6794. configurable: true
  6795. });
  6796. _DepthCullingState.prototype.reset = function () {
  6797. this._depthMask = true;
  6798. this._depthTest = true;
  6799. this._depthFunc = null;
  6800. this._cullFace = null;
  6801. this._cull = null;
  6802. this._zOffset = 0;
  6803. this._isDepthTestDirty = true;
  6804. this._isDepthMaskDirty = true;
  6805. this._isDepthFuncDirty = false;
  6806. this._isCullFaceDirty = false;
  6807. this._isCullDirty = false;
  6808. this._isZOffsetDirty = false;
  6809. };
  6810. _DepthCullingState.prototype.apply = function (gl) {
  6811. if (!this.isDirty) {
  6812. return;
  6813. }
  6814. // Cull
  6815. if (this._isCullDirty) {
  6816. if (this.cull) {
  6817. gl.enable(gl.CULL_FACE);
  6818. }
  6819. else {
  6820. gl.disable(gl.CULL_FACE);
  6821. }
  6822. this._isCullDirty = false;
  6823. }
  6824. // Cull face
  6825. if (this._isCullFaceDirty) {
  6826. gl.cullFace(this.cullFace);
  6827. this._isCullFaceDirty = false;
  6828. }
  6829. // Depth mask
  6830. if (this._isDepthMaskDirty) {
  6831. gl.depthMask(this.depthMask);
  6832. this._isDepthMaskDirty = false;
  6833. }
  6834. // Depth test
  6835. if (this._isDepthTestDirty) {
  6836. if (this.depthTest) {
  6837. gl.enable(gl.DEPTH_TEST);
  6838. }
  6839. else {
  6840. gl.disable(gl.DEPTH_TEST);
  6841. }
  6842. this._isDepthTestDirty = false;
  6843. }
  6844. // Depth func
  6845. if (this._isDepthFuncDirty) {
  6846. gl.depthFunc(this.depthFunc);
  6847. this._isDepthFuncDirty = false;
  6848. }
  6849. // zOffset
  6850. if (this._isZOffsetDirty) {
  6851. if (this.zOffset) {
  6852. gl.enable(gl.POLYGON_OFFSET_FILL);
  6853. gl.polygonOffset(this.zOffset, 0);
  6854. }
  6855. else {
  6856. gl.disable(gl.POLYGON_OFFSET_FILL);
  6857. }
  6858. this._isZOffsetDirty = false;
  6859. }
  6860. };
  6861. return _DepthCullingState;
  6862. }());
  6863. Internals._DepthCullingState = _DepthCullingState;
  6864. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6865. })(BABYLON || (BABYLON = {}));
  6866. //# sourceMappingURL=babylon.depthCullingState.js.map
  6867. var BABYLON;
  6868. (function (BABYLON) {
  6869. var Internals;
  6870. (function (Internals) {
  6871. var _StencilState = (function () {
  6872. function _StencilState() {
  6873. this._isStencilTestDirty = false;
  6874. this._isStencilMaskDirty = false;
  6875. this._isStencilFuncDirty = false;
  6876. this._isStencilOpDirty = false;
  6877. this.reset();
  6878. }
  6879. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6880. get: function () {
  6881. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6882. },
  6883. enumerable: true,
  6884. configurable: true
  6885. });
  6886. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6887. get: function () {
  6888. return this._stencilFunc;
  6889. },
  6890. set: function (value) {
  6891. if (this._stencilFunc === value) {
  6892. return;
  6893. }
  6894. this._stencilFunc = value;
  6895. this._isStencilFuncDirty = true;
  6896. },
  6897. enumerable: true,
  6898. configurable: true
  6899. });
  6900. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6901. get: function () {
  6902. return this._stencilFuncRef;
  6903. },
  6904. set: function (value) {
  6905. if (this._stencilFuncRef === value) {
  6906. return;
  6907. }
  6908. this._stencilFuncRef = value;
  6909. this._isStencilFuncDirty = true;
  6910. },
  6911. enumerable: true,
  6912. configurable: true
  6913. });
  6914. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6915. get: function () {
  6916. return this._stencilFuncMask;
  6917. },
  6918. set: function (value) {
  6919. if (this._stencilFuncMask === value) {
  6920. return;
  6921. }
  6922. this._stencilFuncMask = value;
  6923. this._isStencilFuncDirty = true;
  6924. },
  6925. enumerable: true,
  6926. configurable: true
  6927. });
  6928. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6929. get: function () {
  6930. return this._stencilOpStencilFail;
  6931. },
  6932. set: function (value) {
  6933. if (this._stencilOpStencilFail === value) {
  6934. return;
  6935. }
  6936. this._stencilOpStencilFail = value;
  6937. this._isStencilOpDirty = true;
  6938. },
  6939. enumerable: true,
  6940. configurable: true
  6941. });
  6942. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6943. get: function () {
  6944. return this._stencilOpDepthFail;
  6945. },
  6946. set: function (value) {
  6947. if (this._stencilOpDepthFail === value) {
  6948. return;
  6949. }
  6950. this._stencilOpDepthFail = value;
  6951. this._isStencilOpDirty = true;
  6952. },
  6953. enumerable: true,
  6954. configurable: true
  6955. });
  6956. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6957. get: function () {
  6958. return this._stencilOpStencilDepthPass;
  6959. },
  6960. set: function (value) {
  6961. if (this._stencilOpStencilDepthPass === value) {
  6962. return;
  6963. }
  6964. this._stencilOpStencilDepthPass = value;
  6965. this._isStencilOpDirty = true;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6971. get: function () {
  6972. return this._stencilMask;
  6973. },
  6974. set: function (value) {
  6975. if (this._stencilMask === value) {
  6976. return;
  6977. }
  6978. this._stencilMask = value;
  6979. this._isStencilMaskDirty = true;
  6980. },
  6981. enumerable: true,
  6982. configurable: true
  6983. });
  6984. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6985. get: function () {
  6986. return this._stencilTest;
  6987. },
  6988. set: function (value) {
  6989. if (this._stencilTest === value) {
  6990. return;
  6991. }
  6992. this._stencilTest = value;
  6993. this._isStencilTestDirty = true;
  6994. },
  6995. enumerable: true,
  6996. configurable: true
  6997. });
  6998. _StencilState.prototype.reset = function () {
  6999. this._stencilTest = false;
  7000. this._stencilMask = 0xFF;
  7001. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7002. this._stencilFuncRef = 1;
  7003. this._stencilFuncMask = 0xFF;
  7004. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7005. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7006. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7007. this._isStencilTestDirty = true;
  7008. this._isStencilMaskDirty = true;
  7009. this._isStencilFuncDirty = true;
  7010. this._isStencilOpDirty = true;
  7011. };
  7012. _StencilState.prototype.apply = function (gl) {
  7013. if (!this.isDirty) {
  7014. return;
  7015. }
  7016. // Stencil test
  7017. if (this._isStencilTestDirty) {
  7018. if (this.stencilTest) {
  7019. gl.enable(gl.STENCIL_TEST);
  7020. }
  7021. else {
  7022. gl.disable(gl.STENCIL_TEST);
  7023. }
  7024. this._isStencilTestDirty = false;
  7025. }
  7026. // Stencil mask
  7027. if (this._isStencilMaskDirty) {
  7028. gl.stencilMask(this.stencilMask);
  7029. this._isStencilMaskDirty = false;
  7030. }
  7031. // Stencil func
  7032. if (this._isStencilFuncDirty) {
  7033. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7034. this._isStencilFuncDirty = false;
  7035. }
  7036. // Stencil op
  7037. if (this._isStencilOpDirty) {
  7038. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7039. this._isStencilOpDirty = false;
  7040. }
  7041. };
  7042. return _StencilState;
  7043. }());
  7044. Internals._StencilState = _StencilState;
  7045. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7046. })(BABYLON || (BABYLON = {}));
  7047. //# sourceMappingURL=babylon.stencilState.js.map
  7048. var BABYLON;
  7049. (function (BABYLON) {
  7050. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7051. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7052. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7053. gl.compileShader(shader);
  7054. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7055. throw new Error(gl.getShaderInfoLog(shader));
  7056. }
  7057. return shader;
  7058. };
  7059. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7060. var magFilter = gl.NEAREST;
  7061. var minFilter = gl.NEAREST;
  7062. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7063. magFilter = gl.LINEAR;
  7064. if (generateMipMaps) {
  7065. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7066. }
  7067. else {
  7068. minFilter = gl.LINEAR;
  7069. }
  7070. }
  7071. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7072. magFilter = gl.LINEAR;
  7073. if (generateMipMaps) {
  7074. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7075. }
  7076. else {
  7077. minFilter = gl.LINEAR;
  7078. }
  7079. }
  7080. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7081. magFilter = gl.NEAREST;
  7082. if (generateMipMaps) {
  7083. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7084. }
  7085. else {
  7086. minFilter = gl.NEAREST;
  7087. }
  7088. }
  7089. return {
  7090. min: minFilter,
  7091. mag: magFilter
  7092. };
  7093. };
  7094. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7095. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7096. var engine = scene.getEngine();
  7097. if (!engine) {
  7098. return;
  7099. }
  7100. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7101. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7102. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7103. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7104. texture._baseWidth = width;
  7105. texture._baseHeight = height;
  7106. texture._width = potWidth;
  7107. texture._height = potHeight;
  7108. texture.isReady = true;
  7109. processFunction(potWidth, potHeight);
  7110. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7111. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7113. if (!noMipmap && !isCompressed) {
  7114. gl.generateMipmap(gl.TEXTURE_2D);
  7115. }
  7116. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7117. engine.resetTextureCache();
  7118. scene._removePendingData(texture);
  7119. texture.onLoadedCallbacks.forEach(function (callback) {
  7120. callback();
  7121. });
  7122. texture.onLoadedCallbacks = [];
  7123. };
  7124. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7125. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7126. var img;
  7127. var onload = function () {
  7128. loadedImages[index] = img;
  7129. loadedImages._internalCount++;
  7130. scene._removePendingData(img);
  7131. if (loadedImages._internalCount === 6) {
  7132. onfinish(loadedImages);
  7133. }
  7134. };
  7135. var onerror = function () {
  7136. scene._removePendingData(img);
  7137. if (onErrorCallBack) {
  7138. onErrorCallBack();
  7139. }
  7140. };
  7141. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7142. scene._addPendingData(img);
  7143. };
  7144. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7145. if (onError === void 0) { onError = null; }
  7146. var loadedImages = [];
  7147. loadedImages._internalCount = 0;
  7148. for (var index = 0; index < 6; index++) {
  7149. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7150. }
  7151. };
  7152. var InstancingAttributeInfo = (function () {
  7153. function InstancingAttributeInfo() {
  7154. }
  7155. return InstancingAttributeInfo;
  7156. }());
  7157. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7158. var EngineCapabilities = (function () {
  7159. function EngineCapabilities() {
  7160. }
  7161. return EngineCapabilities;
  7162. }());
  7163. BABYLON.EngineCapabilities = EngineCapabilities;
  7164. /**
  7165. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7166. */
  7167. var Engine = (function () {
  7168. /**
  7169. * @constructor
  7170. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7171. * @param {boolean} [antialias] - enable antialias
  7172. * @param options - further options to be sent to the getContext function
  7173. */
  7174. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7175. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7176. var _this = this;
  7177. // Public members
  7178. this.isFullscreen = false;
  7179. this.isPointerLock = false;
  7180. this.cullBackFaces = true;
  7181. this.renderEvenInBackground = true;
  7182. this.preventCacheWipeBetweenFrames = false;
  7183. // To enable/disable IDB support and avoid XHR on .manifest
  7184. this.enableOfflineSupport = BABYLON.Database;
  7185. this.scenes = new Array();
  7186. // Observables
  7187. /**
  7188. * Observable event triggered each time the rendering canvas is resized
  7189. */
  7190. this.onResizeObservable = new BABYLON.Observable();
  7191. /**
  7192. * Observable event triggered each time the canvas lost focus
  7193. */
  7194. this.onCanvasBlurObservable = new BABYLON.Observable();
  7195. this._windowIsBackground = false;
  7196. this._webGLVersion = 1.0;
  7197. this._badOS = false;
  7198. this._drawCalls = new BABYLON.PerfCounter();
  7199. this._renderingQueueLaunched = false;
  7200. this._activeRenderLoops = [];
  7201. // FPS
  7202. this.fpsRange = 60;
  7203. this.previousFramesDuration = [];
  7204. this.fps = 60;
  7205. this.deltaTime = 0;
  7206. // States
  7207. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7208. this._stencilState = new BABYLON.Internals._StencilState();
  7209. this._alphaState = new BABYLON.Internals._AlphaState();
  7210. this._alphaMode = Engine.ALPHA_DISABLE;
  7211. // Cache
  7212. this._loadedTexturesCache = new Array();
  7213. this._maxTextureChannels = 16;
  7214. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7215. this._compiledEffects = {};
  7216. this._vertexAttribArraysEnabled = [];
  7217. this._uintIndicesCurrentlySet = false;
  7218. this._currentBoundBuffer = new Array();
  7219. this._currentBufferPointers = [];
  7220. this._currentInstanceLocations = new Array();
  7221. this._currentInstanceBuffers = new Array();
  7222. this._vaoRecordInProgress = false;
  7223. this._mustWipeVertexAttributes = false;
  7224. // Hardware supported Compressed Textures
  7225. this._texturesSupported = new Array();
  7226. this._onVRFullScreenTriggered = function () {
  7227. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7228. //get the old size before we change
  7229. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7230. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7231. //get the width and height, change the render size
  7232. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7233. var width, height;
  7234. _this.setHardwareScalingLevel(1);
  7235. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7236. }
  7237. else {
  7238. //When the specs are implemented, need to uncomment this.
  7239. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7240. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7241. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7242. _this._vrDisplayEnabled = undefined;
  7243. }
  7244. };
  7245. this._renderingCanvas = canvas;
  7246. Engine.Instances.push(this);
  7247. options = options || {};
  7248. if (antialias != null) {
  7249. options.antialias = antialias;
  7250. }
  7251. if (options.preserveDrawingBuffer === undefined) {
  7252. options.preserveDrawingBuffer = false;
  7253. }
  7254. if (options.audioEngine === undefined) {
  7255. options.audioEngine = true;
  7256. }
  7257. if (options.stencil === undefined) {
  7258. options.stencil = true;
  7259. }
  7260. // GL
  7261. if (!options.disableWebGL2Support) {
  7262. try {
  7263. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7264. if (this._gl) {
  7265. this._webGLVersion = 2.0;
  7266. }
  7267. }
  7268. catch (e) {
  7269. // Do nothing
  7270. }
  7271. }
  7272. if (!this._gl) {
  7273. if (!canvas) {
  7274. throw new Error("The provided canvas is null or undefined.");
  7275. }
  7276. try {
  7277. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7278. }
  7279. catch (e) {
  7280. throw new Error("WebGL not supported");
  7281. }
  7282. }
  7283. if (!this._gl) {
  7284. throw new Error("WebGL not supported");
  7285. }
  7286. this._onBlur = function () {
  7287. _this._windowIsBackground = true;
  7288. };
  7289. this._onFocus = function () {
  7290. _this._windowIsBackground = false;
  7291. };
  7292. this._onCanvasBlur = function () {
  7293. _this.onCanvasBlurObservable.notifyObservers(_this);
  7294. };
  7295. window.addEventListener("blur", this._onBlur);
  7296. window.addEventListener("focus", this._onFocus);
  7297. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7298. // Viewport
  7299. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7300. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7301. this.resize();
  7302. // Caps
  7303. this._isStencilEnable = options.stencil;
  7304. this._caps = new EngineCapabilities();
  7305. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7306. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7307. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7308. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7309. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7310. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7311. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7312. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7313. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7314. // Infos
  7315. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7316. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7317. if (rendererInfo != null) {
  7318. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7319. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7320. }
  7321. if (!this._glVendor) {
  7322. this._glVendor = "Unknown vendor";
  7323. }
  7324. if (!this._glRenderer) {
  7325. this._glRenderer = "Unknown renderer";
  7326. }
  7327. // Extensions
  7328. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7329. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7330. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7331. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7332. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7333. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7334. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7335. 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');
  7336. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7337. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7338. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7339. this._caps.highPrecisionShaderSupported = true;
  7340. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7341. // Checks if some of the format renders first to allow the use of webgl inspector.
  7342. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7343. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7344. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7345. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7346. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7347. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7348. if (this._webGLVersion > 1) {
  7349. Engine.HALF_FLOAT_OES = 0x140B;
  7350. }
  7351. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7352. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7353. // Vertex array object
  7354. if (this._webGLVersion > 1) {
  7355. this._caps.vertexArrayObject = true;
  7356. }
  7357. else {
  7358. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7359. if (vertexArrayObjectExtension != null) {
  7360. this._caps.vertexArrayObject = true;
  7361. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7362. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7363. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7364. }
  7365. else {
  7366. this._caps.vertexArrayObject = false;
  7367. }
  7368. }
  7369. // Instances count
  7370. if (this._webGLVersion > 1) {
  7371. this._caps.instancedArrays = true;
  7372. }
  7373. else {
  7374. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7375. if (instanceExtension != null) {
  7376. this._caps.instancedArrays = true;
  7377. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7378. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7379. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7380. }
  7381. else {
  7382. this._caps.instancedArrays = false;
  7383. }
  7384. }
  7385. // Intelligently add supported compressed formats in order to check for.
  7386. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7387. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7388. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7389. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7390. if (this._caps.astc)
  7391. this.texturesSupported.push('-astc.ktx');
  7392. if (this._caps.s3tc)
  7393. this.texturesSupported.push('-dxt.ktx');
  7394. if (this._caps.pvrtc)
  7395. this.texturesSupported.push('-pvrtc.ktx');
  7396. if (this._caps.etc2)
  7397. this.texturesSupported.push('-etc2.ktx');
  7398. if (this._caps.etc1)
  7399. this.texturesSupported.push('-etc1.ktx');
  7400. if (this._gl.getShaderPrecisionFormat) {
  7401. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7402. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7403. }
  7404. // Depth buffer
  7405. this.setDepthBuffer(true);
  7406. this.setDepthFunctionToLessOrEqual();
  7407. this.setDepthWrite(true);
  7408. // Fullscreen
  7409. this._onFullscreenChange = function () {
  7410. if (document.fullscreen !== undefined) {
  7411. _this.isFullscreen = document.fullscreen;
  7412. }
  7413. else if (document.mozFullScreen !== undefined) {
  7414. _this.isFullscreen = document.mozFullScreen;
  7415. }
  7416. else if (document.webkitIsFullScreen !== undefined) {
  7417. _this.isFullscreen = document.webkitIsFullScreen;
  7418. }
  7419. else if (document.msIsFullScreen !== undefined) {
  7420. _this.isFullscreen = document.msIsFullScreen;
  7421. }
  7422. // Pointer lock
  7423. if (_this.isFullscreen && _this._pointerLockRequested) {
  7424. canvas.requestPointerLock = canvas.requestPointerLock ||
  7425. canvas.msRequestPointerLock ||
  7426. canvas.mozRequestPointerLock ||
  7427. canvas.webkitRequestPointerLock;
  7428. if (canvas.requestPointerLock) {
  7429. canvas.requestPointerLock();
  7430. }
  7431. }
  7432. };
  7433. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7434. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7435. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7436. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7437. // Pointer lock
  7438. this._onPointerLockChange = function () {
  7439. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7440. document.webkitPointerLockElement === canvas ||
  7441. document.msPointerLockElement === canvas ||
  7442. document.pointerLockElement === canvas);
  7443. };
  7444. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7445. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7446. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7447. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7448. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7449. Engine.audioEngine = new BABYLON.AudioEngine();
  7450. }
  7451. //Load WebVR Devices
  7452. if (options.autoEnableWebVR) {
  7453. this.initWebVR();
  7454. }
  7455. //Detect if we are running on a faulty buggy OS.
  7456. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7457. //ua sniffing is the tool of the devil.
  7458. this._badOS = regexp.test(navigator.userAgent);
  7459. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7460. }
  7461. Object.defineProperty(Engine, "LastCreatedEngine", {
  7462. get: function () {
  7463. if (Engine.Instances.length === 0) {
  7464. return null;
  7465. }
  7466. return Engine.Instances[Engine.Instances.length - 1];
  7467. },
  7468. enumerable: true,
  7469. configurable: true
  7470. });
  7471. Object.defineProperty(Engine, "LastCreatedScene", {
  7472. get: function () {
  7473. var lastCreatedEngine = Engine.LastCreatedEngine;
  7474. if (!lastCreatedEngine) {
  7475. return null;
  7476. }
  7477. if (lastCreatedEngine.scenes.length === 0) {
  7478. return null;
  7479. }
  7480. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7481. },
  7482. enumerable: true,
  7483. configurable: true
  7484. });
  7485. /**
  7486. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7487. */
  7488. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7489. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7490. var engine = Engine.Instances[engineIndex];
  7491. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7492. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7493. }
  7494. }
  7495. };
  7496. Object.defineProperty(Engine, "NEVER", {
  7497. get: function () {
  7498. return Engine._NEVER;
  7499. },
  7500. enumerable: true,
  7501. configurable: true
  7502. });
  7503. Object.defineProperty(Engine, "ALWAYS", {
  7504. get: function () {
  7505. return Engine._ALWAYS;
  7506. },
  7507. enumerable: true,
  7508. configurable: true
  7509. });
  7510. Object.defineProperty(Engine, "LESS", {
  7511. get: function () {
  7512. return Engine._LESS;
  7513. },
  7514. enumerable: true,
  7515. configurable: true
  7516. });
  7517. Object.defineProperty(Engine, "EQUAL", {
  7518. get: function () {
  7519. return Engine._EQUAL;
  7520. },
  7521. enumerable: true,
  7522. configurable: true
  7523. });
  7524. Object.defineProperty(Engine, "LEQUAL", {
  7525. get: function () {
  7526. return Engine._LEQUAL;
  7527. },
  7528. enumerable: true,
  7529. configurable: true
  7530. });
  7531. Object.defineProperty(Engine, "GREATER", {
  7532. get: function () {
  7533. return Engine._GREATER;
  7534. },
  7535. enumerable: true,
  7536. configurable: true
  7537. });
  7538. Object.defineProperty(Engine, "GEQUAL", {
  7539. get: function () {
  7540. return Engine._GEQUAL;
  7541. },
  7542. enumerable: true,
  7543. configurable: true
  7544. });
  7545. Object.defineProperty(Engine, "NOTEQUAL", {
  7546. get: function () {
  7547. return Engine._NOTEQUAL;
  7548. },
  7549. enumerable: true,
  7550. configurable: true
  7551. });
  7552. Object.defineProperty(Engine, "KEEP", {
  7553. get: function () {
  7554. return Engine._KEEP;
  7555. },
  7556. enumerable: true,
  7557. configurable: true
  7558. });
  7559. Object.defineProperty(Engine, "REPLACE", {
  7560. get: function () {
  7561. return Engine._REPLACE;
  7562. },
  7563. enumerable: true,
  7564. configurable: true
  7565. });
  7566. Object.defineProperty(Engine, "INCR", {
  7567. get: function () {
  7568. return Engine._INCR;
  7569. },
  7570. enumerable: true,
  7571. configurable: true
  7572. });
  7573. Object.defineProperty(Engine, "DECR", {
  7574. get: function () {
  7575. return Engine._DECR;
  7576. },
  7577. enumerable: true,
  7578. configurable: true
  7579. });
  7580. Object.defineProperty(Engine, "INVERT", {
  7581. get: function () {
  7582. return Engine._INVERT;
  7583. },
  7584. enumerable: true,
  7585. configurable: true
  7586. });
  7587. Object.defineProperty(Engine, "INCR_WRAP", {
  7588. get: function () {
  7589. return Engine._INCR_WRAP;
  7590. },
  7591. enumerable: true,
  7592. configurable: true
  7593. });
  7594. Object.defineProperty(Engine, "DECR_WRAP", {
  7595. get: function () {
  7596. return Engine._DECR_WRAP;
  7597. },
  7598. enumerable: true,
  7599. configurable: true
  7600. });
  7601. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7602. get: function () {
  7603. return Engine._ALPHA_DISABLE;
  7604. },
  7605. enumerable: true,
  7606. configurable: true
  7607. });
  7608. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7609. get: function () {
  7610. return Engine._ALPHA_ONEONE;
  7611. },
  7612. enumerable: true,
  7613. configurable: true
  7614. });
  7615. Object.defineProperty(Engine, "ALPHA_ADD", {
  7616. get: function () {
  7617. return Engine._ALPHA_ADD;
  7618. },
  7619. enumerable: true,
  7620. configurable: true
  7621. });
  7622. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7623. get: function () {
  7624. return Engine._ALPHA_COMBINE;
  7625. },
  7626. enumerable: true,
  7627. configurable: true
  7628. });
  7629. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7630. get: function () {
  7631. return Engine._ALPHA_SUBTRACT;
  7632. },
  7633. enumerable: true,
  7634. configurable: true
  7635. });
  7636. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7637. get: function () {
  7638. return Engine._ALPHA_MULTIPLY;
  7639. },
  7640. enumerable: true,
  7641. configurable: true
  7642. });
  7643. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7644. get: function () {
  7645. return Engine._ALPHA_MAXIMIZED;
  7646. },
  7647. enumerable: true,
  7648. configurable: true
  7649. });
  7650. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7651. get: function () {
  7652. return Engine._ALPHA_PREMULTIPLIED;
  7653. },
  7654. enumerable: true,
  7655. configurable: true
  7656. });
  7657. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7658. get: function () {
  7659. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7660. },
  7661. enumerable: true,
  7662. configurable: true
  7663. });
  7664. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7665. get: function () {
  7666. return Engine._ALPHA_INTERPOLATE;
  7667. },
  7668. enumerable: true,
  7669. configurable: true
  7670. });
  7671. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7672. get: function () {
  7673. return Engine._ALPHA_SCREENMODE;
  7674. },
  7675. enumerable: true,
  7676. configurable: true
  7677. });
  7678. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7679. get: function () {
  7680. return Engine._DELAYLOADSTATE_NONE;
  7681. },
  7682. enumerable: true,
  7683. configurable: true
  7684. });
  7685. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7686. get: function () {
  7687. return Engine._DELAYLOADSTATE_LOADED;
  7688. },
  7689. enumerable: true,
  7690. configurable: true
  7691. });
  7692. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7693. get: function () {
  7694. return Engine._DELAYLOADSTATE_LOADING;
  7695. },
  7696. enumerable: true,
  7697. configurable: true
  7698. });
  7699. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7700. get: function () {
  7701. return Engine._DELAYLOADSTATE_NOTLOADED;
  7702. },
  7703. enumerable: true,
  7704. configurable: true
  7705. });
  7706. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7707. get: function () {
  7708. return Engine._TEXTUREFORMAT_ALPHA;
  7709. },
  7710. enumerable: true,
  7711. configurable: true
  7712. });
  7713. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7714. get: function () {
  7715. return Engine._TEXTUREFORMAT_LUMINANCE;
  7716. },
  7717. enumerable: true,
  7718. configurable: true
  7719. });
  7720. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7721. get: function () {
  7722. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7723. },
  7724. enumerable: true,
  7725. configurable: true
  7726. });
  7727. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7728. get: function () {
  7729. return Engine._TEXTUREFORMAT_RGB;
  7730. },
  7731. enumerable: true,
  7732. configurable: true
  7733. });
  7734. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7735. get: function () {
  7736. return Engine._TEXTUREFORMAT_RGBA;
  7737. },
  7738. enumerable: true,
  7739. configurable: true
  7740. });
  7741. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7742. get: function () {
  7743. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7744. },
  7745. enumerable: true,
  7746. configurable: true
  7747. });
  7748. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7749. get: function () {
  7750. return Engine._TEXTURETYPE_FLOAT;
  7751. },
  7752. enumerable: true,
  7753. configurable: true
  7754. });
  7755. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7756. get: function () {
  7757. return Engine._TEXTURETYPE_HALF_FLOAT;
  7758. },
  7759. enumerable: true,
  7760. configurable: true
  7761. });
  7762. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7763. get: function () {
  7764. return Engine._SCALEMODE_FLOOR;
  7765. },
  7766. enumerable: true,
  7767. configurable: true
  7768. });
  7769. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7770. get: function () {
  7771. return Engine._SCALEMODE_NEAREST;
  7772. },
  7773. enumerable: true,
  7774. configurable: true
  7775. });
  7776. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7777. get: function () {
  7778. return Engine._SCALEMODE_CEILING;
  7779. },
  7780. enumerable: true,
  7781. configurable: true
  7782. });
  7783. Object.defineProperty(Engine, "Version", {
  7784. get: function () {
  7785. return "3.0-rc";
  7786. },
  7787. enumerable: true,
  7788. configurable: true
  7789. });
  7790. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7791. get: function () {
  7792. return this._texturesSupported;
  7793. },
  7794. enumerable: true,
  7795. configurable: true
  7796. });
  7797. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7798. get: function () {
  7799. return this._textureFormatInUse;
  7800. },
  7801. enumerable: true,
  7802. configurable: true
  7803. });
  7804. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7805. // Empty texture
  7806. get: function () {
  7807. if (!this._emptyTexture) {
  7808. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7809. }
  7810. return this._emptyTexture;
  7811. },
  7812. enumerable: true,
  7813. configurable: true
  7814. });
  7815. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7816. get: function () {
  7817. if (!this._emptyCubeTexture) {
  7818. var faceData = new Uint8Array(4);
  7819. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7820. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7821. }
  7822. return this._emptyCubeTexture;
  7823. },
  7824. enumerable: true,
  7825. configurable: true
  7826. });
  7827. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7828. get: function () {
  7829. return this._webGLVersion;
  7830. },
  7831. enumerable: true,
  7832. configurable: true
  7833. });
  7834. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7835. /**
  7836. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7837. */
  7838. get: function () {
  7839. return this._isStencilEnable;
  7840. },
  7841. enumerable: true,
  7842. configurable: true
  7843. });
  7844. Engine.prototype._prepareWorkingCanvas = function () {
  7845. if (this._workingCanvas) {
  7846. return;
  7847. }
  7848. this._workingCanvas = document.createElement("canvas");
  7849. this._workingContext = this._workingCanvas.getContext("2d");
  7850. };
  7851. Engine.prototype.resetTextureCache = function () {
  7852. for (var index = 0; index < this._maxTextureChannels; index++) {
  7853. this._activeTexturesCache[index] = null;
  7854. }
  7855. };
  7856. Engine.prototype.getGlInfo = function () {
  7857. return {
  7858. vendor: this._glVendor,
  7859. renderer: this._glRenderer,
  7860. version: this._glVersion
  7861. };
  7862. };
  7863. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7864. if (useScreen === void 0) { useScreen = false; }
  7865. var viewport = camera.viewport;
  7866. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7867. };
  7868. Engine.prototype.getRenderWidth = function (useScreen) {
  7869. if (useScreen === void 0) { useScreen = false; }
  7870. if (!useScreen && this._currentRenderTarget) {
  7871. return this._currentRenderTarget._width;
  7872. }
  7873. return this._renderingCanvas.width;
  7874. };
  7875. Engine.prototype.getRenderHeight = function (useScreen) {
  7876. if (useScreen === void 0) { useScreen = false; }
  7877. if (!useScreen && this._currentRenderTarget) {
  7878. return this._currentRenderTarget._height;
  7879. }
  7880. return this._renderingCanvas.height;
  7881. };
  7882. Engine.prototype.getRenderingCanvas = function () {
  7883. return this._renderingCanvas;
  7884. };
  7885. Engine.prototype.getRenderingCanvasClientRect = function () {
  7886. return this._renderingCanvas.getBoundingClientRect();
  7887. };
  7888. Engine.prototype.setHardwareScalingLevel = function (level) {
  7889. this._hardwareScalingLevel = level;
  7890. this.resize();
  7891. };
  7892. Engine.prototype.getHardwareScalingLevel = function () {
  7893. return this._hardwareScalingLevel;
  7894. };
  7895. Engine.prototype.getLoadedTexturesCache = function () {
  7896. return this._loadedTexturesCache;
  7897. };
  7898. Engine.prototype.getCaps = function () {
  7899. return this._caps;
  7900. };
  7901. Object.defineProperty(Engine.prototype, "drawCalls", {
  7902. get: function () {
  7903. return this._drawCalls.current;
  7904. },
  7905. enumerable: true,
  7906. configurable: true
  7907. });
  7908. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7909. get: function () {
  7910. return this._drawCalls;
  7911. },
  7912. enumerable: true,
  7913. configurable: true
  7914. });
  7915. Engine.prototype.getDepthFunction = function () {
  7916. return this._depthCullingState.depthFunc;
  7917. };
  7918. Engine.prototype.setDepthFunction = function (depthFunc) {
  7919. this._depthCullingState.depthFunc = depthFunc;
  7920. };
  7921. Engine.prototype.setDepthFunctionToGreater = function () {
  7922. this._depthCullingState.depthFunc = this._gl.GREATER;
  7923. };
  7924. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7925. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7926. };
  7927. Engine.prototype.setDepthFunctionToLess = function () {
  7928. this._depthCullingState.depthFunc = this._gl.LESS;
  7929. };
  7930. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7931. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7932. };
  7933. Engine.prototype.getStencilBuffer = function () {
  7934. return this._stencilState.stencilTest;
  7935. };
  7936. Engine.prototype.setStencilBuffer = function (enable) {
  7937. this._stencilState.stencilTest = enable;
  7938. };
  7939. Engine.prototype.getStencilMask = function () {
  7940. return this._stencilState.stencilMask;
  7941. };
  7942. Engine.prototype.setStencilMask = function (mask) {
  7943. this._stencilState.stencilMask = mask;
  7944. };
  7945. Engine.prototype.getStencilFunction = function () {
  7946. return this._stencilState.stencilFunc;
  7947. };
  7948. Engine.prototype.getStencilFunctionReference = function () {
  7949. return this._stencilState.stencilFuncRef;
  7950. };
  7951. Engine.prototype.getStencilFunctionMask = function () {
  7952. return this._stencilState.stencilFuncMask;
  7953. };
  7954. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7955. this._stencilState.stencilFunc = stencilFunc;
  7956. };
  7957. Engine.prototype.setStencilFunctionReference = function (reference) {
  7958. this._stencilState.stencilFuncRef = reference;
  7959. };
  7960. Engine.prototype.setStencilFunctionMask = function (mask) {
  7961. this._stencilState.stencilFuncMask = mask;
  7962. };
  7963. Engine.prototype.getStencilOperationFail = function () {
  7964. return this._stencilState.stencilOpStencilFail;
  7965. };
  7966. Engine.prototype.getStencilOperationDepthFail = function () {
  7967. return this._stencilState.stencilOpDepthFail;
  7968. };
  7969. Engine.prototype.getStencilOperationPass = function () {
  7970. return this._stencilState.stencilOpStencilDepthPass;
  7971. };
  7972. Engine.prototype.setStencilOperationFail = function (operation) {
  7973. this._stencilState.stencilOpStencilFail = operation;
  7974. };
  7975. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7976. this._stencilState.stencilOpDepthFail = operation;
  7977. };
  7978. Engine.prototype.setStencilOperationPass = function (operation) {
  7979. this._stencilState.stencilOpStencilDepthPass = operation;
  7980. };
  7981. Engine.prototype.setDitheringState = function (value) {
  7982. if (value) {
  7983. this._gl.enable(this._gl.DITHER);
  7984. }
  7985. else {
  7986. this._gl.disable(this._gl.DITHER);
  7987. }
  7988. };
  7989. /**
  7990. * stop executing a render loop function and remove it from the execution array
  7991. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7992. */
  7993. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7994. if (!renderFunction) {
  7995. this._activeRenderLoops = [];
  7996. return;
  7997. }
  7998. var index = this._activeRenderLoops.indexOf(renderFunction);
  7999. if (index >= 0) {
  8000. this._activeRenderLoops.splice(index, 1);
  8001. }
  8002. };
  8003. Engine.prototype._renderLoop = function () {
  8004. var shouldRender = true;
  8005. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8006. shouldRender = false;
  8007. }
  8008. if (shouldRender) {
  8009. // Start new frame
  8010. this.beginFrame();
  8011. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8012. var renderFunction = this._activeRenderLoops[index];
  8013. renderFunction();
  8014. }
  8015. // Present
  8016. this.endFrame();
  8017. }
  8018. if (this._activeRenderLoops.length > 0) {
  8019. // Register new frame
  8020. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8021. }
  8022. else {
  8023. this._renderingQueueLaunched = false;
  8024. }
  8025. };
  8026. /**
  8027. * Register and execute a render loop. The engine can have more than one render function.
  8028. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8029. * @example
  8030. * engine.runRenderLoop(function () {
  8031. * scene.render()
  8032. * })
  8033. */
  8034. Engine.prototype.runRenderLoop = function (renderFunction) {
  8035. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8036. return;
  8037. }
  8038. this._activeRenderLoops.push(renderFunction);
  8039. if (!this._renderingQueueLaunched) {
  8040. this._renderingQueueLaunched = true;
  8041. this._bindedRenderFunction = this._renderLoop.bind(this);
  8042. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8043. }
  8044. };
  8045. /**
  8046. * Toggle full screen mode.
  8047. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8048. * @param {any} options - an options object to be sent to the requestFullscreen function
  8049. */
  8050. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8051. if (this.isFullscreen) {
  8052. BABYLON.Tools.ExitFullscreen();
  8053. }
  8054. else {
  8055. this._pointerLockRequested = requestPointerLock;
  8056. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8057. }
  8058. };
  8059. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8060. if (stencil === void 0) { stencil = false; }
  8061. this.applyStates();
  8062. var mode = 0;
  8063. if (backBuffer && color) {
  8064. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8065. mode |= this._gl.COLOR_BUFFER_BIT;
  8066. }
  8067. if (depth) {
  8068. this._gl.clearDepth(1.0);
  8069. mode |= this._gl.DEPTH_BUFFER_BIT;
  8070. }
  8071. if (stencil) {
  8072. this._gl.clearStencil(0);
  8073. mode |= this._gl.STENCIL_BUFFER_BIT;
  8074. }
  8075. this._gl.clear(mode);
  8076. };
  8077. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8078. var gl = this._gl;
  8079. // Save state
  8080. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8081. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8082. // Change state
  8083. gl.enable(gl.SCISSOR_TEST);
  8084. gl.scissor(x, y, width, height);
  8085. // Clear
  8086. this.clear(clearColor, true, true, true);
  8087. // Restore state
  8088. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8089. if (curScissor === true) {
  8090. gl.enable(gl.SCISSOR_TEST);
  8091. }
  8092. else {
  8093. gl.disable(gl.SCISSOR_TEST);
  8094. }
  8095. };
  8096. /**
  8097. * Set the WebGL's viewport
  8098. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8099. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8100. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8101. */
  8102. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8103. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8104. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8105. var x = viewport.x || 0;
  8106. var y = viewport.y || 0;
  8107. this._cachedViewport = viewport;
  8108. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8109. };
  8110. /**
  8111. * Directly set the WebGL Viewport
  8112. * The x, y, width & height are directly passed to the WebGL call
  8113. * @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.
  8114. */
  8115. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8116. var currentViewport = this._cachedViewport;
  8117. this._cachedViewport = null;
  8118. this._gl.viewport(x, y, width, height);
  8119. return currentViewport;
  8120. };
  8121. Engine.prototype.beginFrame = function () {
  8122. this._measureFps();
  8123. };
  8124. Engine.prototype.endFrame = function () {
  8125. //force a flush in case we are using a bad OS.
  8126. if (this._badOS) {
  8127. this.flushFramebuffer();
  8128. }
  8129. //submit frame to the vr device, if enabled
  8130. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8131. this._vrDisplayEnabled.submitFrame();
  8132. }
  8133. };
  8134. /**
  8135. * resize the view according to the canvas' size.
  8136. * @example
  8137. * window.addEventListener("resize", function () {
  8138. * engine.resize();
  8139. * });
  8140. */
  8141. Engine.prototype.resize = function () {
  8142. // We're not resizing the size of the canvas while in VR mode & presenting
  8143. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8144. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8145. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8146. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8147. }
  8148. };
  8149. /**
  8150. * force a specific size of the canvas
  8151. * @param {number} width - the new canvas' width
  8152. * @param {number} height - the new canvas' height
  8153. */
  8154. Engine.prototype.setSize = function (width, height) {
  8155. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8156. return;
  8157. }
  8158. this._renderingCanvas.width = width;
  8159. this._renderingCanvas.height = height;
  8160. for (var index = 0; index < this.scenes.length; index++) {
  8161. var scene = this.scenes[index];
  8162. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8163. var cam = scene.cameras[camIndex];
  8164. cam._currentRenderId = 0;
  8165. }
  8166. }
  8167. if (this.onResizeObservable.hasObservers) {
  8168. this.onResizeObservable.notifyObservers(this);
  8169. }
  8170. };
  8171. //WebVR functions
  8172. Engine.prototype.isVRDevicePresent = function (callback) {
  8173. this.getVRDevice(null, function (device) {
  8174. callback(device !== null);
  8175. });
  8176. };
  8177. Engine.prototype.getVRDevice = function (name, callback) {
  8178. if (!this.vrDisplaysPromise) {
  8179. callback(null);
  8180. return;
  8181. }
  8182. this.vrDisplaysPromise.then(function (devices) {
  8183. if (devices.length > 0) {
  8184. if (name) {
  8185. var found = devices.some(function (device) {
  8186. if (device.displayName === name) {
  8187. callback(device);
  8188. return true;
  8189. }
  8190. else {
  8191. return false;
  8192. }
  8193. });
  8194. if (!found) {
  8195. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8196. callback(devices[0]);
  8197. }
  8198. }
  8199. else {
  8200. //choose the first one
  8201. callback(devices[0]);
  8202. }
  8203. }
  8204. else {
  8205. BABYLON.Tools.Error("No WebVR devices found!");
  8206. callback(null);
  8207. }
  8208. });
  8209. };
  8210. Engine.prototype.initWebVR = function () {
  8211. if (!this.vrDisplaysPromise) {
  8212. this._getVRDisplays();
  8213. }
  8214. };
  8215. Engine.prototype.enableVR = function (vrDevice) {
  8216. this._vrDisplayEnabled = vrDevice;
  8217. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8218. };
  8219. Engine.prototype.disableVR = function () {
  8220. if (this._vrDisplayEnabled) {
  8221. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8222. }
  8223. };
  8224. Engine.prototype._getVRDisplays = function () {
  8225. var _this = this;
  8226. var getWebVRDevices = function (devices) {
  8227. var size = devices.length;
  8228. var i = 0;
  8229. _this._vrDisplays = devices.filter(function (device) {
  8230. return devices[i] instanceof VRDisplay;
  8231. });
  8232. return _this._vrDisplays;
  8233. };
  8234. //using a key due to typescript
  8235. if (navigator.getVRDisplays) {
  8236. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8237. }
  8238. };
  8239. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8240. this._currentRenderTarget = texture;
  8241. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8242. var gl = this._gl;
  8243. if (texture.isCube) {
  8244. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8245. }
  8246. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8247. this.wipeCaches();
  8248. };
  8249. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8250. if (this._currentFramebuffer !== framebuffer) {
  8251. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8252. this._currentFramebuffer = framebuffer;
  8253. }
  8254. };
  8255. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8256. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8257. this._currentRenderTarget = null;
  8258. // If MSAA, we need to bitblt back to main texture
  8259. var gl = this._gl;
  8260. if (texture._MSAAFramebuffer) {
  8261. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8262. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8263. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8264. }
  8265. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8266. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8267. gl.generateMipmap(gl.TEXTURE_2D);
  8268. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8269. }
  8270. if (onBeforeUnbind) {
  8271. if (texture._MSAAFramebuffer) {
  8272. // Bind the correct framebuffer
  8273. this.bindUnboundFramebuffer(texture._framebuffer);
  8274. }
  8275. onBeforeUnbind();
  8276. }
  8277. this.bindUnboundFramebuffer(null);
  8278. };
  8279. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8280. if (texture.generateMipMaps) {
  8281. var gl = this._gl;
  8282. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8283. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8284. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8285. }
  8286. };
  8287. Engine.prototype.flushFramebuffer = function () {
  8288. this._gl.flush();
  8289. };
  8290. Engine.prototype.restoreDefaultFramebuffer = function () {
  8291. this._currentRenderTarget = null;
  8292. this.bindUnboundFramebuffer(null);
  8293. if (this._cachedViewport) {
  8294. this.setViewport(this._cachedViewport);
  8295. }
  8296. this.wipeCaches();
  8297. };
  8298. // UBOs
  8299. Engine.prototype.createUniformBuffer = function (elements) {
  8300. var ubo = this._gl.createBuffer();
  8301. this.bindUniformBuffer(ubo);
  8302. if (elements instanceof Float32Array) {
  8303. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8304. }
  8305. else {
  8306. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8307. }
  8308. this.bindUniformBuffer(null);
  8309. ubo.references = 1;
  8310. return ubo;
  8311. };
  8312. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8313. var ubo = this._gl.createBuffer();
  8314. this.bindUniformBuffer(ubo);
  8315. if (elements instanceof Float32Array) {
  8316. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8317. }
  8318. else {
  8319. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8320. }
  8321. this.bindUniformBuffer(null);
  8322. ubo.references = 1;
  8323. return ubo;
  8324. };
  8325. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8326. this.bindUniformBuffer(uniformBuffer);
  8327. if (offset === undefined) {
  8328. offset = 0;
  8329. }
  8330. if (count === undefined) {
  8331. if (elements instanceof Float32Array) {
  8332. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8333. }
  8334. else {
  8335. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8336. }
  8337. }
  8338. else {
  8339. if (elements instanceof Float32Array) {
  8340. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8341. }
  8342. else {
  8343. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8344. }
  8345. }
  8346. this.bindUniformBuffer(null);
  8347. };
  8348. // VBOs
  8349. Engine.prototype._resetVertexBufferBinding = function () {
  8350. this.bindArrayBuffer(null);
  8351. this._cachedVertexBuffers = null;
  8352. };
  8353. Engine.prototype.createVertexBuffer = function (vertices) {
  8354. var vbo = this._gl.createBuffer();
  8355. this.bindArrayBuffer(vbo);
  8356. if (vertices instanceof Float32Array) {
  8357. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8358. }
  8359. else {
  8360. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8361. }
  8362. this._resetVertexBufferBinding();
  8363. vbo.references = 1;
  8364. return vbo;
  8365. };
  8366. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8367. var vbo = this._gl.createBuffer();
  8368. this.bindArrayBuffer(vbo);
  8369. if (vertices instanceof Float32Array) {
  8370. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8371. }
  8372. else {
  8373. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8374. }
  8375. this._resetVertexBufferBinding();
  8376. vbo.references = 1;
  8377. return vbo;
  8378. };
  8379. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8380. this.bindArrayBuffer(vertexBuffer);
  8381. if (offset === undefined) {
  8382. offset = 0;
  8383. }
  8384. if (count === undefined) {
  8385. if (vertices instanceof Float32Array) {
  8386. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8387. }
  8388. else {
  8389. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8390. }
  8391. }
  8392. else {
  8393. if (vertices instanceof Float32Array) {
  8394. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8395. }
  8396. else {
  8397. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8398. }
  8399. }
  8400. this._resetVertexBufferBinding();
  8401. };
  8402. Engine.prototype._resetIndexBufferBinding = function () {
  8403. this.bindIndexBuffer(null);
  8404. this._cachedIndexBuffer = null;
  8405. };
  8406. Engine.prototype.createIndexBuffer = function (indices) {
  8407. var vbo = this._gl.createBuffer();
  8408. this.bindIndexBuffer(vbo);
  8409. // Check for 32 bits indices
  8410. var arrayBuffer;
  8411. var need32Bits = false;
  8412. if (indices instanceof Uint16Array) {
  8413. arrayBuffer = indices;
  8414. }
  8415. else {
  8416. //check 32 bit support
  8417. if (this._caps.uintIndices) {
  8418. if (indices instanceof Uint32Array) {
  8419. arrayBuffer = indices;
  8420. need32Bits = true;
  8421. }
  8422. else {
  8423. //number[] or Int32Array, check if 32 bit is necessary
  8424. for (var index = 0; index < indices.length; index++) {
  8425. if (indices[index] > 65535) {
  8426. need32Bits = true;
  8427. break;
  8428. }
  8429. }
  8430. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8431. }
  8432. }
  8433. else {
  8434. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8435. arrayBuffer = new Uint16Array(indices);
  8436. }
  8437. }
  8438. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8439. this._resetIndexBufferBinding();
  8440. vbo.references = 1;
  8441. vbo.is32Bits = need32Bits;
  8442. return vbo;
  8443. };
  8444. Engine.prototype.bindArrayBuffer = function (buffer) {
  8445. if (!this._vaoRecordInProgress) {
  8446. this._unBindVertexArrayObject();
  8447. }
  8448. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8449. };
  8450. Engine.prototype.bindUniformBuffer = function (buffer) {
  8451. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8452. };
  8453. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8454. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8455. };
  8456. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8457. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8458. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8459. };
  8460. ;
  8461. Engine.prototype.bindIndexBuffer = function (buffer) {
  8462. if (!this._vaoRecordInProgress) {
  8463. this._unBindVertexArrayObject();
  8464. }
  8465. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8466. };
  8467. Engine.prototype.bindBuffer = function (buffer, target) {
  8468. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8469. this._gl.bindBuffer(target, buffer);
  8470. this._currentBoundBuffer[target] = buffer;
  8471. }
  8472. };
  8473. Engine.prototype.updateArrayBuffer = function (data) {
  8474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8475. };
  8476. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8477. var pointer = this._currentBufferPointers[indx];
  8478. var changed = false;
  8479. if (!pointer) {
  8480. changed = true;
  8481. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8482. }
  8483. else {
  8484. if (pointer.buffer !== buffer) {
  8485. pointer.buffer = buffer;
  8486. changed = true;
  8487. }
  8488. if (pointer.size !== size) {
  8489. pointer.size = size;
  8490. changed = true;
  8491. }
  8492. if (pointer.type !== type) {
  8493. pointer.type = type;
  8494. changed = true;
  8495. }
  8496. if (pointer.normalized !== normalized) {
  8497. pointer.normalized = normalized;
  8498. changed = true;
  8499. }
  8500. if (pointer.stride !== stride) {
  8501. pointer.stride = stride;
  8502. changed = true;
  8503. }
  8504. if (pointer.offset !== offset) {
  8505. pointer.offset = offset;
  8506. changed = true;
  8507. }
  8508. }
  8509. if (changed || this._vaoRecordInProgress) {
  8510. this.bindArrayBuffer(buffer);
  8511. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8512. }
  8513. };
  8514. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8515. if (indexBuffer == null) {
  8516. return;
  8517. }
  8518. if (this._cachedIndexBuffer !== indexBuffer) {
  8519. this._cachedIndexBuffer = indexBuffer;
  8520. this.bindIndexBuffer(indexBuffer);
  8521. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8522. }
  8523. };
  8524. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8525. var attributes = effect.getAttributesNames();
  8526. if (!this._vaoRecordInProgress) {
  8527. this._unBindVertexArrayObject();
  8528. }
  8529. this.unbindAllAttributes();
  8530. for (var index = 0; index < attributes.length; index++) {
  8531. var order = effect.getAttributeLocation(index);
  8532. if (order >= 0) {
  8533. var vertexBuffer = vertexBuffers[attributes[index]];
  8534. if (!vertexBuffer) {
  8535. continue;
  8536. }
  8537. this._gl.enableVertexAttribArray(order);
  8538. if (!this._vaoRecordInProgress) {
  8539. this._vertexAttribArraysEnabled[order] = true;
  8540. }
  8541. var buffer = vertexBuffer.getBuffer();
  8542. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8543. if (vertexBuffer.getIsInstanced()) {
  8544. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8545. if (!this._vaoRecordInProgress) {
  8546. this._currentInstanceLocations.push(order);
  8547. this._currentInstanceBuffers.push(buffer);
  8548. }
  8549. }
  8550. }
  8551. }
  8552. };
  8553. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8554. var vao = this._gl.createVertexArray();
  8555. this._vaoRecordInProgress = true;
  8556. this._gl.bindVertexArray(vao);
  8557. this._mustWipeVertexAttributes = true;
  8558. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8559. this.bindIndexBuffer(indexBuffer);
  8560. this._vaoRecordInProgress = false;
  8561. this._gl.bindVertexArray(null);
  8562. return vao;
  8563. };
  8564. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8565. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8566. this._cachedVertexArrayObject = vertexArrayObject;
  8567. this._gl.bindVertexArray(vertexArrayObject);
  8568. this._cachedVertexBuffers = null;
  8569. this._cachedIndexBuffer = null;
  8570. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8571. this._mustWipeVertexAttributes = true;
  8572. }
  8573. };
  8574. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8575. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8576. this._cachedVertexBuffers = vertexBuffer;
  8577. this._cachedEffectForVertexBuffers = effect;
  8578. var attributesCount = effect.getAttributesCount();
  8579. this._unBindVertexArrayObject();
  8580. this.unbindAllAttributes();
  8581. var offset = 0;
  8582. for (var index = 0; index < attributesCount; index++) {
  8583. if (index < vertexDeclaration.length) {
  8584. var order = effect.getAttributeLocation(index);
  8585. if (order >= 0) {
  8586. this._gl.enableVertexAttribArray(order);
  8587. this._vertexAttribArraysEnabled[order] = true;
  8588. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8589. }
  8590. offset += vertexDeclaration[index] * 4;
  8591. }
  8592. }
  8593. }
  8594. this._bindIndexBufferWithCache(indexBuffer);
  8595. };
  8596. Engine.prototype._unBindVertexArrayObject = function () {
  8597. if (!this._cachedVertexArrayObject) {
  8598. return;
  8599. }
  8600. this._cachedVertexArrayObject = null;
  8601. this._gl.bindVertexArray(null);
  8602. };
  8603. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8604. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8605. this._cachedVertexBuffers = vertexBuffers;
  8606. this._cachedEffectForVertexBuffers = effect;
  8607. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8608. }
  8609. this._bindIndexBufferWithCache(indexBuffer);
  8610. };
  8611. Engine.prototype.unbindInstanceAttributes = function () {
  8612. var boundBuffer;
  8613. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8614. var instancesBuffer = this._currentInstanceBuffers[i];
  8615. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8616. boundBuffer = instancesBuffer;
  8617. this.bindArrayBuffer(instancesBuffer);
  8618. }
  8619. var offsetLocation = this._currentInstanceLocations[i];
  8620. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8621. }
  8622. this._currentInstanceBuffers.length = 0;
  8623. this._currentInstanceLocations.length = 0;
  8624. };
  8625. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8626. this._gl.deleteVertexArray(vao);
  8627. };
  8628. Engine.prototype._releaseBuffer = function (buffer) {
  8629. buffer.references--;
  8630. if (buffer.references === 0) {
  8631. this._gl.deleteBuffer(buffer);
  8632. return true;
  8633. }
  8634. return false;
  8635. };
  8636. Engine.prototype.createInstancesBuffer = function (capacity) {
  8637. var buffer = this._gl.createBuffer();
  8638. buffer.capacity = capacity;
  8639. this.bindArrayBuffer(buffer);
  8640. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8641. return buffer;
  8642. };
  8643. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8644. this._gl.deleteBuffer(buffer);
  8645. };
  8646. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8647. this.bindArrayBuffer(instancesBuffer);
  8648. if (data) {
  8649. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8650. }
  8651. if (offsetLocations[0].index !== undefined) {
  8652. var stride = 0;
  8653. for (var i = 0; i < offsetLocations.length; i++) {
  8654. var ai = offsetLocations[i];
  8655. stride += ai.attributeSize * 4;
  8656. }
  8657. for (var i = 0; i < offsetLocations.length; i++) {
  8658. var ai = offsetLocations[i];
  8659. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8660. this._gl.enableVertexAttribArray(ai.index);
  8661. this._vertexAttribArraysEnabled[ai.index] = true;
  8662. }
  8663. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8664. this._gl.vertexAttribDivisor(ai.index, 1);
  8665. this._currentInstanceLocations.push(ai.index);
  8666. this._currentInstanceBuffers.push(instancesBuffer);
  8667. }
  8668. }
  8669. else {
  8670. for (var index = 0; index < 4; index++) {
  8671. var offsetLocation = offsetLocations[index];
  8672. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8673. this._gl.enableVertexAttribArray(offsetLocation);
  8674. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8675. }
  8676. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8677. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8678. this._currentInstanceLocations.push(offsetLocation);
  8679. this._currentInstanceBuffers.push(instancesBuffer);
  8680. }
  8681. }
  8682. };
  8683. Engine.prototype.applyStates = function () {
  8684. this._depthCullingState.apply(this._gl);
  8685. this._stencilState.apply(this._gl);
  8686. this._alphaState.apply(this._gl);
  8687. };
  8688. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8689. // Apply states
  8690. this.applyStates();
  8691. this._drawCalls.addCount(1, false);
  8692. // Render
  8693. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8694. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8695. if (instancesCount) {
  8696. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8697. return;
  8698. }
  8699. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8700. };
  8701. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8702. // Apply states
  8703. this.applyStates();
  8704. this._drawCalls.addCount(1, false);
  8705. if (instancesCount) {
  8706. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8707. return;
  8708. }
  8709. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8710. };
  8711. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8712. // Apply states
  8713. this.applyStates();
  8714. this._drawCalls.addCount(1, false);
  8715. if (instancesCount) {
  8716. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8717. return;
  8718. }
  8719. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8720. };
  8721. // Shaders
  8722. Engine.prototype._releaseEffect = function (effect) {
  8723. if (this._compiledEffects[effect._key]) {
  8724. delete this._compiledEffects[effect._key];
  8725. if (effect.getProgram()) {
  8726. this._gl.deleteProgram(effect.getProgram());
  8727. }
  8728. }
  8729. };
  8730. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8731. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8732. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8733. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8734. if (this._compiledEffects[name]) {
  8735. var compiledEffect = this._compiledEffects[name];
  8736. if (onCompiled && compiledEffect.isReady()) {
  8737. onCompiled(compiledEffect);
  8738. }
  8739. return compiledEffect;
  8740. }
  8741. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8742. effect._key = name;
  8743. this._compiledEffects[name] = effect;
  8744. return effect;
  8745. };
  8746. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8747. if (uniformsNames === void 0) { uniformsNames = []; }
  8748. if (samplers === void 0) { samplers = []; }
  8749. if (defines === void 0) { defines = ""; }
  8750. return this.createEffect({
  8751. vertex: "particles",
  8752. fragmentElement: fragmentName
  8753. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8754. };
  8755. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8756. context = context || this._gl;
  8757. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8758. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8759. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8760. var shaderProgram = context.createProgram();
  8761. context.attachShader(shaderProgram, vertexShader);
  8762. context.attachShader(shaderProgram, fragmentShader);
  8763. context.linkProgram(shaderProgram);
  8764. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8765. if (!linked) {
  8766. var error = context.getProgramInfoLog(shaderProgram);
  8767. if (error) {
  8768. throw new Error(error);
  8769. }
  8770. }
  8771. context.deleteShader(vertexShader);
  8772. context.deleteShader(fragmentShader);
  8773. return shaderProgram;
  8774. };
  8775. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8776. var results = [];
  8777. for (var index = 0; index < uniformsNames.length; index++) {
  8778. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8779. }
  8780. return results;
  8781. };
  8782. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8783. var results = [];
  8784. for (var index = 0; index < attributesNames.length; index++) {
  8785. try {
  8786. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8787. }
  8788. catch (e) {
  8789. results.push(-1);
  8790. }
  8791. }
  8792. return results;
  8793. };
  8794. Engine.prototype.enableEffect = function (effect) {
  8795. // Use program
  8796. this.setProgram(effect.getProgram());
  8797. this._currentEffect = effect;
  8798. if (effect.onBind) {
  8799. effect.onBind(effect);
  8800. }
  8801. effect.onBindObservable.notifyObservers(effect);
  8802. };
  8803. Engine.prototype.setIntArray = function (uniform, array) {
  8804. if (!uniform)
  8805. return;
  8806. this._gl.uniform1iv(uniform, array);
  8807. };
  8808. Engine.prototype.setIntArray2 = function (uniform, array) {
  8809. if (!uniform || array.length % 2 !== 0)
  8810. return;
  8811. this._gl.uniform2iv(uniform, array);
  8812. };
  8813. Engine.prototype.setIntArray3 = function (uniform, array) {
  8814. if (!uniform || array.length % 3 !== 0)
  8815. return;
  8816. this._gl.uniform3iv(uniform, array);
  8817. };
  8818. Engine.prototype.setIntArray4 = function (uniform, array) {
  8819. if (!uniform || array.length % 4 !== 0)
  8820. return;
  8821. this._gl.uniform4iv(uniform, array);
  8822. };
  8823. Engine.prototype.setFloatArray = function (uniform, array) {
  8824. if (!uniform)
  8825. return;
  8826. this._gl.uniform1fv(uniform, array);
  8827. };
  8828. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8829. if (!uniform || array.length % 2 !== 0)
  8830. return;
  8831. this._gl.uniform2fv(uniform, array);
  8832. };
  8833. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8834. if (!uniform || array.length % 3 !== 0)
  8835. return;
  8836. this._gl.uniform3fv(uniform, array);
  8837. };
  8838. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8839. if (!uniform || array.length % 4 !== 0)
  8840. return;
  8841. this._gl.uniform4fv(uniform, array);
  8842. };
  8843. Engine.prototype.setArray = function (uniform, array) {
  8844. if (!uniform)
  8845. return;
  8846. this._gl.uniform1fv(uniform, array);
  8847. };
  8848. Engine.prototype.setArray2 = function (uniform, array) {
  8849. if (!uniform || array.length % 2 !== 0)
  8850. return;
  8851. this._gl.uniform2fv(uniform, array);
  8852. };
  8853. Engine.prototype.setArray3 = function (uniform, array) {
  8854. if (!uniform || array.length % 3 !== 0)
  8855. return;
  8856. this._gl.uniform3fv(uniform, array);
  8857. };
  8858. Engine.prototype.setArray4 = function (uniform, array) {
  8859. if (!uniform || array.length % 4 !== 0)
  8860. return;
  8861. this._gl.uniform4fv(uniform, array);
  8862. };
  8863. Engine.prototype.setMatrices = function (uniform, matrices) {
  8864. if (!uniform)
  8865. return;
  8866. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8867. };
  8868. Engine.prototype.setMatrix = function (uniform, matrix) {
  8869. if (!uniform)
  8870. return;
  8871. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8872. };
  8873. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8874. if (!uniform)
  8875. return;
  8876. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8877. };
  8878. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8879. if (!uniform)
  8880. return;
  8881. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8882. };
  8883. Engine.prototype.setFloat = function (uniform, value) {
  8884. if (!uniform)
  8885. return;
  8886. this._gl.uniform1f(uniform, value);
  8887. };
  8888. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8889. if (!uniform)
  8890. return;
  8891. this._gl.uniform2f(uniform, x, y);
  8892. };
  8893. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8894. if (!uniform)
  8895. return;
  8896. this._gl.uniform3f(uniform, x, y, z);
  8897. };
  8898. Engine.prototype.setBool = function (uniform, bool) {
  8899. if (!uniform)
  8900. return;
  8901. this._gl.uniform1i(uniform, bool);
  8902. };
  8903. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8904. if (!uniform)
  8905. return;
  8906. this._gl.uniform4f(uniform, x, y, z, w);
  8907. };
  8908. Engine.prototype.setColor3 = function (uniform, color3) {
  8909. if (!uniform)
  8910. return;
  8911. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8912. };
  8913. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8914. if (!uniform)
  8915. return;
  8916. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8917. };
  8918. // States
  8919. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8920. if (zOffset === void 0) { zOffset = 0; }
  8921. if (reverseSide === void 0) { reverseSide = false; }
  8922. // Culling
  8923. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8924. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8925. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8926. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8927. if (culling) {
  8928. this._depthCullingState.cullFace = cullFace;
  8929. this._depthCullingState.cull = true;
  8930. }
  8931. else {
  8932. this._depthCullingState.cull = false;
  8933. }
  8934. }
  8935. // Z offset
  8936. this.setZOffset(zOffset);
  8937. };
  8938. Engine.prototype.setZOffset = function (value) {
  8939. this._depthCullingState.zOffset = value;
  8940. };
  8941. Engine.prototype.getZOffset = function () {
  8942. return this._depthCullingState.zOffset;
  8943. };
  8944. Engine.prototype.setDepthBuffer = function (enable) {
  8945. this._depthCullingState.depthTest = enable;
  8946. };
  8947. Engine.prototype.getDepthWrite = function () {
  8948. return this._depthCullingState.depthMask;
  8949. };
  8950. Engine.prototype.setDepthWrite = function (enable) {
  8951. this._depthCullingState.depthMask = enable;
  8952. };
  8953. Engine.prototype.setColorWrite = function (enable) {
  8954. this._gl.colorMask(enable, enable, enable, enable);
  8955. };
  8956. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8957. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8958. };
  8959. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8960. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8961. if (this._alphaMode === mode) {
  8962. return;
  8963. }
  8964. switch (mode) {
  8965. case Engine.ALPHA_DISABLE:
  8966. this._alphaState.alphaBlend = false;
  8967. break;
  8968. case Engine.ALPHA_PREMULTIPLIED:
  8969. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8970. this._alphaState.alphaBlend = true;
  8971. break;
  8972. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8973. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8974. this._alphaState.alphaBlend = true;
  8975. break;
  8976. case Engine.ALPHA_COMBINE:
  8977. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8978. this._alphaState.alphaBlend = true;
  8979. break;
  8980. case Engine.ALPHA_ONEONE:
  8981. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8982. this._alphaState.alphaBlend = true;
  8983. break;
  8984. case Engine.ALPHA_ADD:
  8985. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8986. this._alphaState.alphaBlend = true;
  8987. break;
  8988. case Engine.ALPHA_SUBTRACT:
  8989. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8990. this._alphaState.alphaBlend = true;
  8991. break;
  8992. case Engine.ALPHA_MULTIPLY:
  8993. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8994. this._alphaState.alphaBlend = true;
  8995. break;
  8996. case Engine.ALPHA_MAXIMIZED:
  8997. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8998. this._alphaState.alphaBlend = true;
  8999. break;
  9000. case Engine.ALPHA_INTERPOLATE:
  9001. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9002. this._alphaState.alphaBlend = true;
  9003. break;
  9004. case Engine.ALPHA_SCREENMODE:
  9005. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9006. this._alphaState.alphaBlend = true;
  9007. break;
  9008. }
  9009. if (!noDepthWriteChange) {
  9010. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9011. }
  9012. this._alphaMode = mode;
  9013. };
  9014. Engine.prototype.getAlphaMode = function () {
  9015. return this._alphaMode;
  9016. };
  9017. Engine.prototype.setAlphaTesting = function (enable) {
  9018. this._alphaTest = enable;
  9019. };
  9020. Engine.prototype.getAlphaTesting = function () {
  9021. return !!this._alphaTest;
  9022. };
  9023. // Textures
  9024. Engine.prototype.wipeCaches = function (bruteForce) {
  9025. if (this.preventCacheWipeBetweenFrames) {
  9026. return;
  9027. }
  9028. this.resetTextureCache();
  9029. this._currentEffect = null;
  9030. // 6/8/2017: deltakosh: Should not be required anymore.
  9031. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9032. if (bruteForce) {
  9033. this._stencilState.reset();
  9034. this._depthCullingState.reset();
  9035. this.setDepthFunctionToLessOrEqual();
  9036. this._alphaState.reset();
  9037. }
  9038. this._cachedVertexBuffers = null;
  9039. this._cachedIndexBuffer = null;
  9040. this._cachedEffectForVertexBuffers = null;
  9041. this._unBindVertexArrayObject();
  9042. this.bindIndexBuffer(null);
  9043. this.bindArrayBuffer(null);
  9044. };
  9045. /**
  9046. * Set the compressed texture format to use, based on the formats you have, and the formats
  9047. * supported by the hardware / browser.
  9048. *
  9049. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9050. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9051. * to API arguments needed to compressed textures. This puts the burden on the container
  9052. * generator to house the arcane code for determining these for current & future formats.
  9053. *
  9054. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9055. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9056. *
  9057. * Note: The result of this call is not taken into account when a texture is base64.
  9058. *
  9059. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9060. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9061. *
  9062. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9063. * @returns The extension selected.
  9064. */
  9065. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9066. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9067. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9068. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9069. return this._textureFormatInUse = this._texturesSupported[i];
  9070. }
  9071. }
  9072. }
  9073. // actively set format to nothing, to allow this to be called more than once
  9074. // and possibly fail the 2nd time
  9075. return this._textureFormatInUse = null;
  9076. };
  9077. /**
  9078. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9079. * @param {string} urlArg- This contains one of the following:
  9080. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9081. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9082. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9083. *
  9084. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9085. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9086. * @param {Scene} scene- Needed for loading to the correct scene.
  9087. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9088. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9089. * @param {callback} onError- Optional callback to be called upon failure.
  9090. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9091. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9092. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9093. *
  9094. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9095. */
  9096. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9097. var _this = this;
  9098. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9099. if (onLoad === void 0) { onLoad = null; }
  9100. if (onError === void 0) { onError = null; }
  9101. if (buffer === void 0) { buffer = null; }
  9102. var texture = fallBack ? fallBack : this._gl.createTexture();
  9103. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9104. var fromData = url.substr(0, 5) === "data:";
  9105. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9106. // establish the file extension, if possible
  9107. var lastDot = url.lastIndexOf('.');
  9108. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9109. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9110. if (isDDS) {
  9111. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9112. }
  9113. var isTGA = (extension === ".tga");
  9114. // determine if a ktx file should be substituted
  9115. var isKTX = false;
  9116. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9117. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9118. isKTX = true;
  9119. }
  9120. scene._addPendingData(texture);
  9121. texture.url = url;
  9122. texture.noMipmap = noMipmap;
  9123. texture.references = 1;
  9124. texture.samplingMode = samplingMode;
  9125. texture.onLoadedCallbacks = [];
  9126. if (onLoad) {
  9127. texture.onLoadedCallbacks.push(onLoad);
  9128. }
  9129. if (!fallBack)
  9130. this._loadedTexturesCache.push(texture);
  9131. var onerror = function () {
  9132. scene._removePendingData(texture);
  9133. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9134. if (isKTX) {
  9135. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9136. }
  9137. else if (onError) {
  9138. onError();
  9139. }
  9140. };
  9141. var callback;
  9142. // processing for non-image formats
  9143. if (isKTX || isTGA || isDDS) {
  9144. if (isKTX) {
  9145. callback = function (data) {
  9146. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9147. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9148. ktx.uploadLevels(_this._gl, !noMipmap);
  9149. }, samplingMode);
  9150. };
  9151. }
  9152. else if (isTGA) {
  9153. callback = function (arrayBuffer) {
  9154. var data = new Uint8Array(arrayBuffer);
  9155. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9156. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9157. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9158. }, samplingMode);
  9159. };
  9160. }
  9161. else if (isDDS) {
  9162. callback = function (data) {
  9163. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9164. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9165. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9166. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9167. }, samplingMode);
  9168. };
  9169. }
  9170. if (!buffer) {
  9171. BABYLON.Tools.LoadFile(url, function (data) {
  9172. callback(data);
  9173. }, null, scene.database, true, onerror);
  9174. }
  9175. else {
  9176. callback(buffer);
  9177. }
  9178. // image format processing
  9179. }
  9180. else {
  9181. var onload = function (img) {
  9182. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9183. var isPot = (img.width === potWidth && img.height === potHeight);
  9184. if (!isPot) {
  9185. _this._prepareWorkingCanvas();
  9186. _this._workingCanvas.width = potWidth;
  9187. _this._workingCanvas.height = potHeight;
  9188. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9189. _this._workingContext.imageSmoothingEnabled = false;
  9190. _this._workingContext.mozImageSmoothingEnabled = false;
  9191. _this._workingContext.oImageSmoothingEnabled = false;
  9192. _this._workingContext.webkitImageSmoothingEnabled = false;
  9193. _this._workingContext.msImageSmoothingEnabled = false;
  9194. }
  9195. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9196. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9197. _this._workingContext.imageSmoothingEnabled = true;
  9198. _this._workingContext.mozImageSmoothingEnabled = true;
  9199. _this._workingContext.oImageSmoothingEnabled = true;
  9200. _this._workingContext.webkitImageSmoothingEnabled = true;
  9201. _this._workingContext.msImageSmoothingEnabled = true;
  9202. }
  9203. }
  9204. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9205. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9206. }, samplingMode);
  9207. };
  9208. if (!fromData || isBase64)
  9209. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9210. else if (buffer instanceof Array || typeof buffer === "string")
  9211. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9212. else
  9213. onload(buffer);
  9214. }
  9215. return texture;
  9216. };
  9217. Engine.prototype._getInternalFormat = function (format) {
  9218. var internalFormat = this._gl.RGBA;
  9219. switch (format) {
  9220. case Engine.TEXTUREFORMAT_ALPHA:
  9221. internalFormat = this._gl.ALPHA;
  9222. break;
  9223. case Engine.TEXTUREFORMAT_LUMINANCE:
  9224. internalFormat = this._gl.LUMINANCE;
  9225. break;
  9226. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9227. internalFormat = this._gl.LUMINANCE_ALPHA;
  9228. break;
  9229. case Engine.TEXTUREFORMAT_RGB:
  9230. internalFormat = this._gl.RGB;
  9231. break;
  9232. case Engine.TEXTUREFORMAT_RGBA:
  9233. internalFormat = this._gl.RGBA;
  9234. break;
  9235. }
  9236. return internalFormat;
  9237. };
  9238. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9239. if (compression === void 0) { compression = null; }
  9240. var internalFormat = this._getInternalFormat(format);
  9241. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9242. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9243. if (texture._width % 4 !== 0) {
  9244. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9245. }
  9246. if (compression) {
  9247. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9248. }
  9249. else {
  9250. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9251. }
  9252. if (texture.generateMipMaps) {
  9253. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9254. }
  9255. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9256. this.resetTextureCache();
  9257. texture.isReady = true;
  9258. };
  9259. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9260. if (compression === void 0) { compression = null; }
  9261. var texture = this._gl.createTexture();
  9262. texture._baseWidth = width;
  9263. texture._baseHeight = height;
  9264. texture._width = width;
  9265. texture._height = height;
  9266. texture.references = 1;
  9267. this.updateRawTexture(texture, data, format, invertY, compression);
  9268. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9269. // Filters
  9270. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9271. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9272. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9273. if (generateMipMaps) {
  9274. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9275. }
  9276. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9277. texture.samplingMode = samplingMode;
  9278. this._loadedTexturesCache.push(texture);
  9279. return texture;
  9280. };
  9281. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9282. var texture = this._gl.createTexture();
  9283. texture._baseWidth = width;
  9284. texture._baseHeight = height;
  9285. if (generateMipMaps) {
  9286. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9287. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9288. }
  9289. this.resetTextureCache();
  9290. texture._width = width;
  9291. texture._height = height;
  9292. texture.isReady = false;
  9293. texture.generateMipMaps = generateMipMaps;
  9294. texture.references = 1;
  9295. texture.samplingMode = samplingMode;
  9296. this.updateTextureSamplingMode(samplingMode, texture);
  9297. this._loadedTexturesCache.push(texture);
  9298. return texture;
  9299. };
  9300. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9301. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9302. if (texture.isCube) {
  9303. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9304. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9305. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9306. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9307. }
  9308. else {
  9309. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9310. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9311. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9312. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9313. }
  9314. texture.samplingMode = samplingMode;
  9315. };
  9316. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9317. if (premulAlpha === void 0) { premulAlpha = false; }
  9318. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9319. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9320. if (premulAlpha) {
  9321. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9322. }
  9323. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9324. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9325. if (texture.generateMipMaps) {
  9326. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9327. }
  9328. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9329. if (premulAlpha) {
  9330. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9331. }
  9332. this.resetTextureCache();
  9333. texture.isReady = true;
  9334. };
  9335. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9336. if (texture._isDisabled) {
  9337. return;
  9338. }
  9339. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9340. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9341. try {
  9342. // Testing video texture support
  9343. if (this._videoTextureSupported === undefined) {
  9344. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9345. if (this._gl.getError() !== 0) {
  9346. this._videoTextureSupported = false;
  9347. }
  9348. else {
  9349. this._videoTextureSupported = true;
  9350. }
  9351. }
  9352. // Copy video through the current working canvas if video texture is not supported
  9353. if (!this._videoTextureSupported) {
  9354. if (!texture._workingCanvas) {
  9355. texture._workingCanvas = document.createElement("canvas");
  9356. texture._workingContext = texture._workingCanvas.getContext("2d");
  9357. texture._workingCanvas.width = texture._width;
  9358. texture._workingCanvas.height = texture._height;
  9359. }
  9360. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9361. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9362. }
  9363. else {
  9364. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9365. }
  9366. if (texture.generateMipMaps) {
  9367. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9368. }
  9369. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9370. this.resetTextureCache();
  9371. texture.isReady = true;
  9372. }
  9373. catch (ex) {
  9374. // Something unexpected
  9375. // Let's disable the texture
  9376. texture._isDisabled = true;
  9377. }
  9378. };
  9379. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9380. // old version had a "generateMipMaps" arg instead of options.
  9381. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9382. // in the same way, generateDepthBuffer is defaulted to true
  9383. var generateMipMaps = false;
  9384. var generateDepthBuffer = true;
  9385. var generateStencilBuffer = false;
  9386. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9387. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9388. if (options !== undefined) {
  9389. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9390. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9391. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9392. type = options.type === undefined ? type : options.type;
  9393. if (options.samplingMode !== undefined) {
  9394. samplingMode = options.samplingMode;
  9395. }
  9396. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9397. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9398. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9399. }
  9400. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9401. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9402. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9403. }
  9404. }
  9405. var gl = this._gl;
  9406. var texture = gl.createTexture();
  9407. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9408. var width = size.width || size;
  9409. var height = size.height || size;
  9410. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9411. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9412. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9413. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9414. }
  9415. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9416. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9417. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9418. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9419. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9420. // Create the framebuffer
  9421. var framebuffer = gl.createFramebuffer();
  9422. this.bindUnboundFramebuffer(framebuffer);
  9423. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9424. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9425. if (generateMipMaps) {
  9426. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9427. }
  9428. // Unbind
  9429. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9430. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9431. this.bindUnboundFramebuffer(null);
  9432. texture._framebuffer = framebuffer;
  9433. texture._baseWidth = width;
  9434. texture._baseHeight = height;
  9435. texture._width = width;
  9436. texture._height = height;
  9437. texture.isReady = true;
  9438. texture.samples = 1;
  9439. texture.generateMipMaps = generateMipMaps;
  9440. texture.references = 1;
  9441. texture.samplingMode = samplingMode;
  9442. texture.type = type;
  9443. texture._generateDepthBuffer = generateDepthBuffer;
  9444. texture._generateStencilBuffer = generateStencilBuffer;
  9445. this.resetTextureCache();
  9446. this._loadedTexturesCache.push(texture);
  9447. return texture;
  9448. };
  9449. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9450. var generateMipMaps = false;
  9451. var generateDepthBuffer = true;
  9452. var generateStencilBuffer = false;
  9453. var generateDepthTexture = false;
  9454. var textureCount = 1;
  9455. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9456. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9457. var types = [], samplingModes = [];
  9458. if (options !== undefined) {
  9459. generateMipMaps = options.generateMipMaps;
  9460. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9461. generateStencilBuffer = options.generateStencilBuffer;
  9462. generateDepthTexture = options.generateDepthTexture;
  9463. textureCount = options.textureCount || 1;
  9464. if (options.types) {
  9465. types = options.types;
  9466. }
  9467. if (options.samplingModes) {
  9468. samplingModes = options.samplingModes;
  9469. }
  9470. }
  9471. var gl = this._gl;
  9472. // Create the framebuffer
  9473. var framebuffer = gl.createFramebuffer();
  9474. this.bindUnboundFramebuffer(framebuffer);
  9475. var width = size.width || size;
  9476. var height = size.height || size;
  9477. var textures = [];
  9478. var attachments = [];
  9479. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9480. for (var i = 0; i < textureCount; i++) {
  9481. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9482. var type = types[i] || defaultType;
  9483. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9484. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9485. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9486. }
  9487. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9488. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9489. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9490. }
  9491. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9492. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9493. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9494. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9495. }
  9496. var texture = gl.createTexture();
  9497. var attachment = gl["COLOR_ATTACHMENT" + i];
  9498. textures.push(texture);
  9499. attachments.push(attachment);
  9500. gl.activeTexture(gl["TEXTURE" + i]);
  9501. gl.bindTexture(gl.TEXTURE_2D, texture);
  9502. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9503. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9504. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9505. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9506. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9507. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9508. if (generateMipMaps) {
  9509. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9510. }
  9511. // Unbind
  9512. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9513. texture._framebuffer = framebuffer;
  9514. texture._depthStencilBuffer = depthStencilBuffer;
  9515. texture._baseWidth = width;
  9516. texture._baseHeight = height;
  9517. texture._width = width;
  9518. texture._height = height;
  9519. texture.isReady = true;
  9520. texture.samples = 1;
  9521. texture.generateMipMaps = generateMipMaps;
  9522. texture.references = 1;
  9523. texture.samplingMode = samplingMode;
  9524. texture.type = type;
  9525. texture._generateDepthBuffer = generateDepthBuffer;
  9526. texture._generateStencilBuffer = generateStencilBuffer;
  9527. this._loadedTexturesCache.push(texture);
  9528. }
  9529. if (generateDepthTexture) {
  9530. // Depth texture
  9531. var depthTexture = gl.createTexture();
  9532. gl.activeTexture(gl.TEXTURE0);
  9533. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9534. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9535. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9536. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9537. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9538. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9539. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9540. depthTexture._framebuffer = framebuffer;
  9541. depthTexture._baseWidth = width;
  9542. depthTexture._baseHeight = height;
  9543. depthTexture._width = width;
  9544. depthTexture._height = height;
  9545. depthTexture.isReady = true;
  9546. depthTexture.samples = 1;
  9547. depthTexture.generateMipMaps = generateMipMaps;
  9548. depthTexture.references = 1;
  9549. depthTexture.samplingMode = gl.NEAREST;
  9550. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9551. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9552. textures.push(depthTexture);
  9553. this._loadedTexturesCache.push(depthTexture);
  9554. }
  9555. gl.drawBuffers(attachments);
  9556. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9557. this.bindUnboundFramebuffer(null);
  9558. this.resetTextureCache();
  9559. return textures;
  9560. };
  9561. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9562. if (samples === void 0) { samples = 1; }
  9563. var depthStencilBuffer = null;
  9564. var gl = this._gl;
  9565. // Create the depth/stencil buffer
  9566. if (generateStencilBuffer) {
  9567. depthStencilBuffer = gl.createRenderbuffer();
  9568. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9569. if (samples > 1) {
  9570. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9571. }
  9572. else {
  9573. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9574. }
  9575. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9576. }
  9577. else if (generateDepthBuffer) {
  9578. depthStencilBuffer = gl.createRenderbuffer();
  9579. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9580. if (samples > 1) {
  9581. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9582. }
  9583. else {
  9584. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9585. }
  9586. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9587. }
  9588. return depthStencilBuffer;
  9589. };
  9590. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9591. if (this.webGLVersion < 2) {
  9592. return 1;
  9593. }
  9594. if (texture.samples === samples) {
  9595. return samples;
  9596. }
  9597. var gl = this._gl;
  9598. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9599. // Dispose previous render buffers
  9600. if (texture._depthStencilBuffer) {
  9601. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9602. }
  9603. if (texture._MSAAFramebuffer) {
  9604. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9605. }
  9606. if (texture._MSAARenderBuffer) {
  9607. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9608. }
  9609. if (samples > 1) {
  9610. texture._MSAAFramebuffer = gl.createFramebuffer();
  9611. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9612. var colorRenderbuffer = gl.createRenderbuffer();
  9613. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9614. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9615. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9616. texture._MSAARenderBuffer = colorRenderbuffer;
  9617. }
  9618. else {
  9619. this.bindUnboundFramebuffer(texture._framebuffer);
  9620. }
  9621. texture.samples = samples;
  9622. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9623. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9624. this.bindUnboundFramebuffer(null);
  9625. return samples;
  9626. };
  9627. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9628. var gl = this._gl;
  9629. var texture = gl.createTexture();
  9630. var generateMipMaps = true;
  9631. var generateDepthBuffer = true;
  9632. var generateStencilBuffer = false;
  9633. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9634. if (options !== undefined) {
  9635. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9636. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9637. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9638. if (options.samplingMode !== undefined) {
  9639. samplingMode = options.samplingMode;
  9640. }
  9641. }
  9642. texture.isCube = true;
  9643. texture.references = 1;
  9644. texture.generateMipMaps = generateMipMaps;
  9645. texture.references = 1;
  9646. texture.samples = 1;
  9647. texture.samplingMode = samplingMode;
  9648. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9649. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9650. for (var face = 0; face < 6; face++) {
  9651. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9652. }
  9653. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9654. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9656. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9657. // Create the framebuffer
  9658. var framebuffer = gl.createFramebuffer();
  9659. this.bindUnboundFramebuffer(framebuffer);
  9660. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9661. // Mipmaps
  9662. if (texture.generateMipMaps) {
  9663. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9664. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9665. }
  9666. // Unbind
  9667. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9668. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9669. this.bindUnboundFramebuffer(null);
  9670. texture._framebuffer = framebuffer;
  9671. texture._width = size;
  9672. texture._height = size;
  9673. texture.isReady = true;
  9674. this.resetTextureCache();
  9675. this._loadedTexturesCache.push(texture);
  9676. return texture;
  9677. };
  9678. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9679. var _this = this;
  9680. if (onLoad === void 0) { onLoad = null; }
  9681. if (onError === void 0) { onError = null; }
  9682. var gl = this._gl;
  9683. var texture = gl.createTexture();
  9684. texture.isCube = true;
  9685. texture.url = rootUrl;
  9686. texture.references = 1;
  9687. texture.onLoadedCallbacks = [];
  9688. var isKTX = false;
  9689. var lastDot = rootUrl.lastIndexOf('.');
  9690. var extension = rootUrl.substring(lastDot).toLowerCase();
  9691. if (this._textureFormatInUse) {
  9692. extension = this._textureFormatInUse;
  9693. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9694. isKTX = true;
  9695. }
  9696. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9697. if (isDDS) {
  9698. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9699. }
  9700. if (isKTX) {
  9701. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9702. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9703. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9704. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9705. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9706. ktx.uploadLevels(_this._gl, !noMipmap);
  9707. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9708. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9709. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9710. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9711. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9712. _this.resetTextureCache();
  9713. texture._width = ktx.pixelWidth;
  9714. texture._height = ktx.pixelHeight;
  9715. texture.isReady = true;
  9716. }, null, null, true, onError);
  9717. }
  9718. else if (isDDS) {
  9719. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9720. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9721. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9722. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9723. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9724. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9725. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9726. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9727. }
  9728. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9729. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9731. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9732. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9733. _this.resetTextureCache();
  9734. texture._width = info.width;
  9735. texture._height = info.height;
  9736. texture.isReady = true;
  9737. }, null, null, true, onError);
  9738. }
  9739. else {
  9740. cascadeLoad(rootUrl, scene, function (imgs) {
  9741. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9742. var height = width;
  9743. _this._prepareWorkingCanvas();
  9744. _this._workingCanvas.width = width;
  9745. _this._workingCanvas.height = height;
  9746. var faces = [
  9747. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9748. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9749. ];
  9750. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9751. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9752. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9753. for (var index = 0; index < faces.length; index++) {
  9754. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9755. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9756. }
  9757. if (!noMipmap) {
  9758. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9759. }
  9760. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9761. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9762. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9764. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9765. _this.resetTextureCache();
  9766. texture._width = width;
  9767. texture._height = height;
  9768. texture.isReady = true;
  9769. texture.onLoadedCallbacks.forEach(function (callback) {
  9770. callback();
  9771. });
  9772. if (onLoad) {
  9773. onLoad();
  9774. }
  9775. }, files, onError);
  9776. }
  9777. this._loadedTexturesCache.push(texture);
  9778. return texture;
  9779. };
  9780. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9781. texture._width = width;
  9782. texture._height = height;
  9783. texture._size = width * height;
  9784. texture._baseWidth = width;
  9785. texture._baseHeight = height;
  9786. };
  9787. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9788. if (compression === void 0) { compression = null; }
  9789. if (level === void 0) { level = 0; }
  9790. var gl = this._gl;
  9791. var textureType = this._getWebGLTextureType(type);
  9792. var internalFormat = this._getInternalFormat(format);
  9793. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9794. var needConversion = false;
  9795. if (internalFormat === gl.RGB) {
  9796. internalFormat = gl.RGBA;
  9797. needConversion = true;
  9798. }
  9799. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9800. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9801. if (texture._width % 4 !== 0) {
  9802. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9803. }
  9804. var facesIndex = [
  9805. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9806. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9807. ];
  9808. // Data are known to be in +X +Y +Z -X -Y -Z
  9809. for (var index = 0; index < facesIndex.length; index++) {
  9810. var faceData = data[index];
  9811. if (compression) {
  9812. gl.compressedTexImage2D(facesIndex[index], level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9813. }
  9814. else {
  9815. if (needConversion) {
  9816. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9817. }
  9818. gl.texImage2D(facesIndex[index], level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9819. }
  9820. }
  9821. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9822. if (isPot && texture.generateMipMaps && level === 0) {
  9823. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9824. }
  9825. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9826. this.resetTextureCache();
  9827. texture.isReady = true;
  9828. };
  9829. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9830. if (compression === void 0) { compression = null; }
  9831. var gl = this._gl;
  9832. var texture = gl.createTexture();
  9833. texture.isCube = true;
  9834. texture.references = 1;
  9835. var textureType = this._getWebGLTextureType(type);
  9836. var internalFormat = this._getInternalFormat(format);
  9837. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9838. var needConversion = false;
  9839. if (internalFormat === gl.RGB) {
  9840. internalFormat = gl.RGBA;
  9841. needConversion = true;
  9842. }
  9843. var width = size;
  9844. var height = width;
  9845. texture._width = width;
  9846. texture._height = height;
  9847. // Double check on POT to generate Mips.
  9848. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9849. if (!isPot) {
  9850. generateMipMaps = false;
  9851. }
  9852. texture.generateMipMaps = generateMipMaps;
  9853. // Upload data if needed. The texture won t be ready until then.
  9854. if (data) {
  9855. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9856. }
  9857. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9858. // Filters
  9859. if (data && generateMipMaps) {
  9860. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9861. }
  9862. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9863. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9865. }
  9866. else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9867. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9868. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9869. }
  9870. else {
  9871. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9872. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9873. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9874. }
  9875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9877. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9878. this._loadedTexturesCache.push(texture);
  9879. return texture;
  9880. };
  9881. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9882. var _this = this;
  9883. if (onLoad === void 0) { onLoad = null; }
  9884. if (onError === void 0) { onError = null; }
  9885. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9886. if (invertY === void 0) { invertY = false; }
  9887. var gl = this._gl;
  9888. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9889. scene._addPendingData(texture);
  9890. texture.url = url;
  9891. var onerror = function () {
  9892. scene._removePendingData(texture);
  9893. if (onError) {
  9894. onError();
  9895. }
  9896. };
  9897. var internalCallback = function (data) {
  9898. var rgbeDataArrays = callback(data);
  9899. var facesIndex = [
  9900. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9901. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9902. ];
  9903. var width = texture._width;
  9904. var height = texture._height;
  9905. if (mipmmapGenerator) {
  9906. // TODO Remove this once Proper CubeMap Blur... This has nothing to do in engine...
  9907. // I ll remove ASAP.
  9908. var textureType = _this._getWebGLTextureType(type);
  9909. var internalFormat = _this._getInternalFormat(format);
  9910. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9911. var needConversion = false;
  9912. if (internalFormat === gl.RGB) {
  9913. internalFormat = gl.RGBA;
  9914. needConversion = true;
  9915. }
  9916. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9917. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9918. var arrayTemp = [];
  9919. // Data are known to be in +X +Y +Z -X -Y -Z
  9920. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9921. arrayTemp.push(rgbeDataArrays[0]); // +X
  9922. arrayTemp.push(rgbeDataArrays[3]); // -X
  9923. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9924. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9925. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9926. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9927. var mipData = mipmmapGenerator(arrayTemp);
  9928. // mipData is order in +X -X +Y -Y +Z -Z
  9929. var mipFaces = [0, 2, 4, 1, 3, 5];
  9930. for (var level = 0; level < mipData.length; level++) {
  9931. var mipSize = width >> level;
  9932. for (var mipIndex in mipFaces) {
  9933. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9934. if (needConversion) {
  9935. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9936. }
  9937. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9938. }
  9939. }
  9940. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9941. }
  9942. else {
  9943. texture.generateMipMaps = !noMipmap;
  9944. _this.updateRawCubeTexture(texture, rgbeDataArrays, format, type, invertY);
  9945. }
  9946. texture.isReady = true;
  9947. _this.resetTextureCache();
  9948. scene._removePendingData(texture);
  9949. if (onLoad) {
  9950. onLoad();
  9951. }
  9952. };
  9953. BABYLON.Tools.LoadFile(url, function (data) {
  9954. internalCallback(data);
  9955. }, onerror, scene.database, true);
  9956. return texture;
  9957. };
  9958. ;
  9959. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9960. // Create new RGBA data container.
  9961. var rgbaData;
  9962. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9963. rgbaData = new Float32Array(width * height * 4);
  9964. }
  9965. else {
  9966. rgbaData = new Uint32Array(width * height * 4);
  9967. }
  9968. // Convert each pixel.
  9969. for (var x = 0; x < width; x++) {
  9970. for (var y = 0; y < height; y++) {
  9971. var index = (y * width + x) * 3;
  9972. var newIndex = (y * width + x) * 4;
  9973. // Map Old Value to new value.
  9974. rgbaData[newIndex + 0] = rgbData[index + 0];
  9975. rgbaData[newIndex + 1] = rgbData[index + 1];
  9976. rgbaData[newIndex + 2] = rgbData[index + 2];
  9977. // Add fully opaque alpha channel.
  9978. rgbaData[newIndex + 3] = 1;
  9979. }
  9980. }
  9981. return rgbaData;
  9982. };
  9983. Engine.prototype._releaseFramebufferObjects = function (texture) {
  9984. var gl = this._gl;
  9985. if (texture._framebuffer) {
  9986. gl.deleteFramebuffer(texture._framebuffer);
  9987. texture._framebuffer = null;
  9988. }
  9989. if (texture._depthStencilBuffer) {
  9990. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9991. texture._depthStencilBuffer = null;
  9992. }
  9993. if (texture._MSAAFramebuffer) {
  9994. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9995. texture._MSAAFramebuffer = null;
  9996. }
  9997. if (texture._MSAARenderBuffer) {
  9998. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9999. texture._MSAARenderBuffer = null;
  10000. }
  10001. };
  10002. Engine.prototype._releaseTexture = function (texture) {
  10003. var gl = this._gl;
  10004. this._releaseFramebufferObjects(texture);
  10005. gl.deleteTexture(texture);
  10006. // Unbind channels
  10007. this.unbindAllTextures();
  10008. var index = this._loadedTexturesCache.indexOf(texture);
  10009. if (index !== -1) {
  10010. this._loadedTexturesCache.splice(index, 1);
  10011. }
  10012. };
  10013. Engine.prototype.setProgram = function (program) {
  10014. if (this._currentProgram !== program) {
  10015. this._gl.useProgram(program);
  10016. this._currentProgram = program;
  10017. }
  10018. };
  10019. Engine.prototype.bindSamplers = function (effect) {
  10020. this.setProgram(effect.getProgram());
  10021. var samplers = effect.getSamplers();
  10022. for (var index = 0; index < samplers.length; index++) {
  10023. var uniform = effect.getUniform(samplers[index]);
  10024. this._gl.uniform1i(uniform, index);
  10025. }
  10026. this._currentEffect = null;
  10027. };
  10028. Engine.prototype.activateTexture = function (texture) {
  10029. if (this._activeTexture !== texture) {
  10030. this._gl.activeTexture(texture);
  10031. this._activeTexture = texture;
  10032. }
  10033. };
  10034. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10035. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10036. this._gl.bindTexture(target, texture);
  10037. this._activeTexturesCache[this._activeTexture] = texture;
  10038. }
  10039. };
  10040. Engine.prototype._bindTexture = function (channel, texture) {
  10041. if (channel < 0) {
  10042. return;
  10043. }
  10044. this.activateTexture(this._gl.TEXTURE0 + channel);
  10045. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10046. };
  10047. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10048. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10049. };
  10050. Engine.prototype.unbindAllTextures = function () {
  10051. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10052. this.activateTexture(this._gl["TEXTURE" + channel]);
  10053. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10054. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10055. }
  10056. };
  10057. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10058. if (channel < 0) {
  10059. return;
  10060. }
  10061. this._gl.uniform1i(uniform, channel);
  10062. this._setTexture(channel, texture);
  10063. };
  10064. Engine.prototype._setTexture = function (channel, texture) {
  10065. // Not ready?
  10066. if (!texture) {
  10067. if (this._activeTexturesCache[channel] != null) {
  10068. this.activateTexture(this._gl["TEXTURE" + channel]);
  10069. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10070. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10071. }
  10072. return;
  10073. }
  10074. // Video
  10075. var alreadyActivated = false;
  10076. if (texture.video) {
  10077. this.activateTexture(this._gl["TEXTURE" + channel]);
  10078. alreadyActivated = true;
  10079. texture.update();
  10080. }
  10081. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10082. texture.delayLoad();
  10083. return;
  10084. }
  10085. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10086. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10087. if (this._activeTexturesCache[channel] === internalTexture) {
  10088. return;
  10089. }
  10090. if (!alreadyActivated) {
  10091. this.activateTexture(this._gl["TEXTURE" + channel]);
  10092. }
  10093. if (internalTexture.isCube) {
  10094. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10095. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10096. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10097. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10098. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10099. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10100. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10101. }
  10102. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10103. }
  10104. else {
  10105. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10106. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10107. internalTexture._cachedWrapU = texture.wrapU;
  10108. switch (texture.wrapU) {
  10109. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10110. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10111. break;
  10112. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10113. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10114. break;
  10115. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10116. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10117. break;
  10118. }
  10119. }
  10120. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10121. internalTexture._cachedWrapV = texture.wrapV;
  10122. switch (texture.wrapV) {
  10123. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10124. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10125. break;
  10126. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10127. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10128. break;
  10129. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10130. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10131. break;
  10132. }
  10133. }
  10134. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10135. }
  10136. };
  10137. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10138. if (channel < 0) {
  10139. return;
  10140. }
  10141. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10142. this._textureUnits = new Int32Array(textures.length);
  10143. }
  10144. for (var i = 0; i < textures.length; i++) {
  10145. this._textureUnits[i] = channel + i;
  10146. }
  10147. this._gl.uniform1iv(uniform, this._textureUnits);
  10148. for (var index = 0; index < textures.length; index++) {
  10149. this._setTexture(channel + index, textures[index]);
  10150. }
  10151. };
  10152. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10153. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10154. var value = texture.anisotropicFilteringLevel;
  10155. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10156. value = 1;
  10157. }
  10158. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10159. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10160. texture._cachedAnisotropicFilteringLevel = value;
  10161. }
  10162. };
  10163. Engine.prototype.readPixels = function (x, y, width, height) {
  10164. var data = new Uint8Array(height * width * 4);
  10165. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10166. return data;
  10167. };
  10168. /**
  10169. * Add an externaly attached data from its key.
  10170. * This method call will fail and return false, if such key already exists.
  10171. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10172. * @param key the unique key that identifies the data
  10173. * @param data the data object to associate to the key for this Engine instance
  10174. * @return true if no such key were already present and the data was added successfully, false otherwise
  10175. */
  10176. Engine.prototype.addExternalData = function (key, data) {
  10177. if (!this._externalData) {
  10178. this._externalData = new BABYLON.StringDictionary();
  10179. }
  10180. return this._externalData.add(key, data);
  10181. };
  10182. /**
  10183. * Get an externaly attached data from its key
  10184. * @param key the unique key that identifies the data
  10185. * @return the associated data, if present (can be null), or undefined if not present
  10186. */
  10187. Engine.prototype.getExternalData = function (key) {
  10188. if (!this._externalData) {
  10189. this._externalData = new BABYLON.StringDictionary();
  10190. }
  10191. return this._externalData.get(key);
  10192. };
  10193. /**
  10194. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10195. * @param key the unique key that identifies the data
  10196. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10197. * @return the associated data, can be null if the factory returned null.
  10198. */
  10199. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10200. if (!this._externalData) {
  10201. this._externalData = new BABYLON.StringDictionary();
  10202. }
  10203. return this._externalData.getOrAddWithFactory(key, factory);
  10204. };
  10205. /**
  10206. * Remove an externaly attached data from the Engine instance
  10207. * @param key the unique key that identifies the data
  10208. * @return true if the data was successfully removed, false if it doesn't exist
  10209. */
  10210. Engine.prototype.removeExternalData = function (key) {
  10211. if (!this._externalData) {
  10212. this._externalData = new BABYLON.StringDictionary();
  10213. }
  10214. return this._externalData.remove(key);
  10215. };
  10216. Engine.prototype.releaseInternalTexture = function (texture) {
  10217. if (!texture) {
  10218. return;
  10219. }
  10220. texture.references--;
  10221. // Final reference ?
  10222. if (texture.references === 0) {
  10223. var texturesCache = this.getLoadedTexturesCache();
  10224. var index = texturesCache.indexOf(texture);
  10225. if (index > -1) {
  10226. texturesCache.splice(index, 1);
  10227. }
  10228. this._releaseTexture(texture);
  10229. }
  10230. };
  10231. Engine.prototype.unbindAllAttributes = function () {
  10232. if (this._mustWipeVertexAttributes) {
  10233. this._mustWipeVertexAttributes = false;
  10234. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10235. this._gl.disableVertexAttribArray(i);
  10236. this._vertexAttribArraysEnabled[i] = false;
  10237. this._currentBufferPointers[i] = null;
  10238. }
  10239. return;
  10240. }
  10241. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10242. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10243. continue;
  10244. }
  10245. this._gl.disableVertexAttribArray(i);
  10246. this._vertexAttribArraysEnabled[i] = false;
  10247. this._currentBufferPointers[i] = null;
  10248. }
  10249. };
  10250. Engine.prototype.releaseEffects = function () {
  10251. for (var name in this._compiledEffects) {
  10252. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10253. }
  10254. this._compiledEffects = {};
  10255. };
  10256. // Dispose
  10257. Engine.prototype.dispose = function () {
  10258. this.hideLoadingUI();
  10259. this.stopRenderLoop();
  10260. // Empty texture
  10261. if (this._emptyTexture) {
  10262. this._releaseTexture(this._emptyTexture);
  10263. this._emptyTexture = null;
  10264. }
  10265. if (this._emptyCubeTexture) {
  10266. this._releaseTexture(this._emptyCubeTexture);
  10267. this._emptyCubeTexture = null;
  10268. }
  10269. // Release scenes
  10270. while (this.scenes.length) {
  10271. this.scenes[0].dispose();
  10272. }
  10273. // Release audio engine
  10274. if (Engine.audioEngine) {
  10275. Engine.audioEngine.dispose();
  10276. }
  10277. // Release effects
  10278. this.releaseEffects();
  10279. // Unbind
  10280. this.unbindAllAttributes();
  10281. if (this._dummyFramebuffer) {
  10282. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10283. }
  10284. this._gl = null;
  10285. //WebVR
  10286. this.disableVR();
  10287. // Events
  10288. window.removeEventListener("blur", this._onBlur);
  10289. window.removeEventListener("focus", this._onFocus);
  10290. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10291. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10292. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10293. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10294. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10295. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10296. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10297. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10298. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10299. // Remove from Instances
  10300. var index = Engine.Instances.indexOf(this);
  10301. if (index >= 0) {
  10302. Engine.Instances.splice(index, 1);
  10303. }
  10304. };
  10305. // Loading screen
  10306. Engine.prototype.displayLoadingUI = function () {
  10307. var loadingScreen = this.loadingScreen;
  10308. if (loadingScreen) {
  10309. loadingScreen.displayLoadingUI();
  10310. }
  10311. };
  10312. Engine.prototype.hideLoadingUI = function () {
  10313. var loadingScreen = this.loadingScreen;
  10314. if (loadingScreen) {
  10315. loadingScreen.hideLoadingUI();
  10316. }
  10317. };
  10318. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10319. get: function () {
  10320. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10321. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10322. return this._loadingScreen;
  10323. },
  10324. set: function (loadingScreen) {
  10325. this._loadingScreen = loadingScreen;
  10326. },
  10327. enumerable: true,
  10328. configurable: true
  10329. });
  10330. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10331. set: function (text) {
  10332. this.loadingScreen.loadingUIText = text;
  10333. },
  10334. enumerable: true,
  10335. configurable: true
  10336. });
  10337. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10338. set: function (color) {
  10339. this.loadingScreen.loadingUIBackgroundColor = color;
  10340. },
  10341. enumerable: true,
  10342. configurable: true
  10343. });
  10344. Engine.prototype.attachContextLostEvent = function (callback) {
  10345. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10346. };
  10347. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10348. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10349. };
  10350. Engine.prototype.getVertexShaderSource = function (program) {
  10351. var shaders = this._gl.getAttachedShaders(program);
  10352. return this._gl.getShaderSource(shaders[0]);
  10353. };
  10354. Engine.prototype.getFragmentShaderSource = function (program) {
  10355. var shaders = this._gl.getAttachedShaders(program);
  10356. return this._gl.getShaderSource(shaders[1]);
  10357. };
  10358. Engine.prototype.getError = function () {
  10359. return this._gl.getError();
  10360. };
  10361. // FPS
  10362. Engine.prototype.getFps = function () {
  10363. return this.fps;
  10364. };
  10365. Engine.prototype.getDeltaTime = function () {
  10366. return this.deltaTime;
  10367. };
  10368. Engine.prototype._measureFps = function () {
  10369. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10370. var length = this.previousFramesDuration.length;
  10371. if (length >= 2) {
  10372. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10373. }
  10374. if (length >= this.fpsRange) {
  10375. if (length > this.fpsRange) {
  10376. this.previousFramesDuration.splice(0, 1);
  10377. length = this.previousFramesDuration.length;
  10378. }
  10379. var sum = 0;
  10380. for (var id = 0; id < length - 1; id++) {
  10381. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10382. }
  10383. this.fps = 1000.0 / (sum / (length - 1));
  10384. }
  10385. };
  10386. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10387. if (faceIndex === void 0) { faceIndex = -1; }
  10388. var gl = this._gl;
  10389. if (!this._dummyFramebuffer) {
  10390. this._dummyFramebuffer = gl.createFramebuffer();
  10391. }
  10392. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10393. if (faceIndex > -1) {
  10394. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  10395. }
  10396. else {
  10397. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10398. }
  10399. var readFormat = gl.RGBA;
  10400. var readType = gl.UNSIGNED_BYTE;
  10401. var buffer = new Uint8Array(4 * width * height);
  10402. gl.readPixels(0, 0, width, height, readFormat, readType, buffer);
  10403. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10404. return buffer;
  10405. };
  10406. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10407. if (this._webGLVersion > 1) {
  10408. return this._caps.colorBufferFloat;
  10409. }
  10410. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10411. };
  10412. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10413. if (this._webGLVersion > 1) {
  10414. return this._caps.colorBufferFloat;
  10415. }
  10416. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10417. };
  10418. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10419. Engine.prototype._canRenderToFramebuffer = function (type) {
  10420. var gl = this._gl;
  10421. //clear existing errors
  10422. while (gl.getError() !== gl.NO_ERROR) { }
  10423. var successful = true;
  10424. var texture = gl.createTexture();
  10425. gl.bindTexture(gl.TEXTURE_2D, texture);
  10426. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10427. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10428. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10429. var fb = gl.createFramebuffer();
  10430. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10431. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10432. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10433. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10434. successful = successful && (gl.getError() === gl.NO_ERROR);
  10435. //try render by clearing frame buffer's color buffer
  10436. if (successful) {
  10437. gl.clear(gl.COLOR_BUFFER_BIT);
  10438. successful = successful && (gl.getError() === gl.NO_ERROR);
  10439. }
  10440. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10441. if (successful) {
  10442. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10443. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10444. var readFormat = gl.RGBA;
  10445. var readType = gl.UNSIGNED_BYTE;
  10446. var buffer = new Uint8Array(4);
  10447. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10448. successful = successful && (gl.getError() === gl.NO_ERROR);
  10449. }
  10450. //clean up
  10451. gl.deleteTexture(texture);
  10452. gl.deleteFramebuffer(fb);
  10453. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10454. //clear accumulated errors
  10455. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10456. return successful;
  10457. };
  10458. Engine.prototype._getWebGLTextureType = function (type) {
  10459. if (type === Engine.TEXTURETYPE_FLOAT) {
  10460. return this._gl.FLOAT;
  10461. }
  10462. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10463. // Add Half Float Constant.
  10464. return Engine.HALF_FLOAT_OES;
  10465. }
  10466. return this._gl.UNSIGNED_BYTE;
  10467. };
  10468. ;
  10469. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10470. if (this._webGLVersion === 1) {
  10471. return this._gl.RGBA;
  10472. }
  10473. if (type === Engine.TEXTURETYPE_FLOAT) {
  10474. return Engine.RGBA32F;
  10475. }
  10476. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10477. return Engine.RGBA16F;
  10478. }
  10479. return this._gl.RGBA;
  10480. };
  10481. ;
  10482. // Statics
  10483. Engine.isSupported = function () {
  10484. try {
  10485. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10486. if (navigator.isCocoonJS) {
  10487. return true;
  10488. }
  10489. var tempcanvas = document.createElement("canvas");
  10490. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10491. return gl != null && !!window.WebGLRenderingContext;
  10492. }
  10493. catch (e) {
  10494. return false;
  10495. }
  10496. };
  10497. return Engine;
  10498. }());
  10499. Engine.Instances = new Array();
  10500. // Const statics
  10501. Engine._ALPHA_DISABLE = 0;
  10502. Engine._ALPHA_ADD = 1;
  10503. Engine._ALPHA_COMBINE = 2;
  10504. Engine._ALPHA_SUBTRACT = 3;
  10505. Engine._ALPHA_MULTIPLY = 4;
  10506. Engine._ALPHA_MAXIMIZED = 5;
  10507. Engine._ALPHA_ONEONE = 6;
  10508. Engine._ALPHA_PREMULTIPLIED = 7;
  10509. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10510. Engine._ALPHA_INTERPOLATE = 9;
  10511. Engine._ALPHA_SCREENMODE = 10;
  10512. Engine._DELAYLOADSTATE_NONE = 0;
  10513. Engine._DELAYLOADSTATE_LOADED = 1;
  10514. Engine._DELAYLOADSTATE_LOADING = 2;
  10515. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10516. Engine._TEXTUREFORMAT_ALPHA = 0;
  10517. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10518. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10519. Engine._TEXTUREFORMAT_RGB = 4;
  10520. Engine._TEXTUREFORMAT_RGBA = 5;
  10521. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10522. Engine._TEXTURETYPE_FLOAT = 1;
  10523. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10524. // Depht or Stencil test Constants.
  10525. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10526. 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.
  10527. 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.
  10528. 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.
  10529. 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.
  10530. 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.
  10531. 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.
  10532. 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.
  10533. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10534. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10535. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10536. // Stencil Actions Constants.
  10537. Engine._KEEP = 0x1E00;
  10538. Engine._REPLACE = 0x1E01;
  10539. Engine._INCR = 0x1E02;
  10540. Engine._DECR = 0x1E03;
  10541. Engine._INVERT = 0x150A;
  10542. Engine._INCR_WRAP = 0x8507;
  10543. Engine._DECR_WRAP = 0x8508;
  10544. // Texture rescaling mode
  10545. Engine._SCALEMODE_FLOOR = 1;
  10546. Engine._SCALEMODE_NEAREST = 2;
  10547. Engine._SCALEMODE_CEILING = 3;
  10548. // Updatable statics so stick with vars here
  10549. Engine.CollisionsEpsilon = 0.001;
  10550. Engine.CodeRepository = "src/";
  10551. Engine.ShadersRepository = "src/Shaders/";
  10552. BABYLON.Engine = Engine;
  10553. })(BABYLON || (BABYLON = {}));
  10554. //# sourceMappingURL=babylon.engine.js.map
  10555. /// <reference path="Tools\babylon.decorators.ts" />
  10556. var BABYLON;
  10557. (function (BABYLON) {
  10558. /**
  10559. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10560. */
  10561. var Node = (function () {
  10562. /**
  10563. * @constructor
  10564. * @param {string} name - the name and id to be given to this node
  10565. * @param {BABYLON.Scene} the scene this node will be added to
  10566. */
  10567. function Node(name, scene) {
  10568. this.state = "";
  10569. this.metadata = null;
  10570. this.doNotSerialize = false;
  10571. this.animations = new Array();
  10572. this._ranges = {};
  10573. this._childrenFlag = -1;
  10574. this._isEnabled = true;
  10575. this._isReady = true;
  10576. this._currentRenderId = -1;
  10577. this._parentRenderId = -1;
  10578. /**
  10579. * An event triggered when the mesh is disposed.
  10580. * @type {BABYLON.Observable}
  10581. */
  10582. this.onDisposeObservable = new BABYLON.Observable();
  10583. this.name = name;
  10584. this.id = name;
  10585. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10586. this._initCache();
  10587. }
  10588. Object.defineProperty(Node.prototype, "parent", {
  10589. get: function () {
  10590. return this._parentNode;
  10591. },
  10592. set: function (parent) {
  10593. if (this._parentNode === parent) {
  10594. return;
  10595. }
  10596. if (this._parentNode) {
  10597. var index = this._parentNode._children.indexOf(this);
  10598. if (index !== -1) {
  10599. this._parentNode._children.splice(index, 1);
  10600. }
  10601. }
  10602. this._parentNode = parent;
  10603. if (this._parentNode) {
  10604. if (!this._parentNode._children) {
  10605. this._parentNode._children = new Array();
  10606. }
  10607. this._parentNode._children.push(this);
  10608. }
  10609. },
  10610. enumerable: true,
  10611. configurable: true
  10612. });
  10613. Node.prototype.getClassName = function () {
  10614. return "Node";
  10615. };
  10616. Object.defineProperty(Node.prototype, "onDispose", {
  10617. set: function (callback) {
  10618. if (this._onDisposeObserver) {
  10619. this.onDisposeObservable.remove(this._onDisposeObserver);
  10620. }
  10621. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10622. },
  10623. enumerable: true,
  10624. configurable: true
  10625. });
  10626. Node.prototype.getScene = function () {
  10627. return this._scene;
  10628. };
  10629. Node.prototype.getEngine = function () {
  10630. return this._scene.getEngine();
  10631. };
  10632. // override it in derived class
  10633. Node.prototype.getWorldMatrix = function () {
  10634. return BABYLON.Matrix.Identity();
  10635. };
  10636. // override it in derived class if you add new variables to the cache
  10637. // and call the parent class method
  10638. Node.prototype._initCache = function () {
  10639. this._cache = {};
  10640. this._cache.parent = undefined;
  10641. };
  10642. Node.prototype.updateCache = function (force) {
  10643. if (!force && this.isSynchronized())
  10644. return;
  10645. this._cache.parent = this.parent;
  10646. this._updateCache();
  10647. };
  10648. // override it in derived class if you add new variables to the cache
  10649. // and call the parent class method if !ignoreParentClass
  10650. Node.prototype._updateCache = function (ignoreParentClass) {
  10651. };
  10652. // override it in derived class if you add new variables to the cache
  10653. Node.prototype._isSynchronized = function () {
  10654. return true;
  10655. };
  10656. Node.prototype._markSyncedWithParent = function () {
  10657. this._parentRenderId = this.parent._currentRenderId;
  10658. };
  10659. Node.prototype.isSynchronizedWithParent = function () {
  10660. if (!this.parent) {
  10661. return true;
  10662. }
  10663. if (this._parentRenderId !== this.parent._currentRenderId) {
  10664. return false;
  10665. }
  10666. return this.parent.isSynchronized();
  10667. };
  10668. Node.prototype.isSynchronized = function (updateCache) {
  10669. var check = this.hasNewParent();
  10670. check = check || !this.isSynchronizedWithParent();
  10671. check = check || !this._isSynchronized();
  10672. if (updateCache)
  10673. this.updateCache(true);
  10674. return !check;
  10675. };
  10676. Node.prototype.hasNewParent = function (update) {
  10677. if (this._cache.parent === this.parent)
  10678. return false;
  10679. if (update)
  10680. this._cache.parent = this.parent;
  10681. return true;
  10682. };
  10683. /**
  10684. * Is this node ready to be used/rendered
  10685. * @return {boolean} is it ready
  10686. */
  10687. Node.prototype.isReady = function () {
  10688. return this._isReady;
  10689. };
  10690. /**
  10691. * Is this node enabled.
  10692. * If the node has a parent and is enabled, the parent will be inspected as well.
  10693. * @return {boolean} whether this node (and its parent) is enabled.
  10694. * @see setEnabled
  10695. */
  10696. Node.prototype.isEnabled = function () {
  10697. if (!this._isEnabled) {
  10698. return false;
  10699. }
  10700. if (this.parent) {
  10701. return this.parent.isEnabled();
  10702. }
  10703. return true;
  10704. };
  10705. /**
  10706. * Set the enabled state of this node.
  10707. * @param {boolean} value - the new enabled state
  10708. * @see isEnabled
  10709. */
  10710. Node.prototype.setEnabled = function (value) {
  10711. this._isEnabled = value;
  10712. };
  10713. /**
  10714. * Is this node a descendant of the given node.
  10715. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10716. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10717. * @see parent
  10718. */
  10719. Node.prototype.isDescendantOf = function (ancestor) {
  10720. if (this.parent) {
  10721. if (this.parent === ancestor) {
  10722. return true;
  10723. }
  10724. return this.parent.isDescendantOf(ancestor);
  10725. }
  10726. return false;
  10727. };
  10728. /**
  10729. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10730. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10731. * @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.
  10732. * @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.
  10733. */
  10734. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10735. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10736. if (!this._children) {
  10737. return;
  10738. }
  10739. for (var index = 0; index < this._children.length; index++) {
  10740. var item = this._children[index];
  10741. if (!predicate || predicate(item)) {
  10742. results.push(item);
  10743. }
  10744. if (!directDescendantsOnly) {
  10745. item._getDescendants(results, false, predicate);
  10746. }
  10747. }
  10748. };
  10749. /**
  10750. * Will return all nodes that have this node as ascendant.
  10751. * @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.
  10752. * @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.
  10753. * @return {BABYLON.Node[]} all children nodes of all types.
  10754. */
  10755. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10756. var results = [];
  10757. this._getDescendants(results, directDescendantsOnly, predicate);
  10758. return results;
  10759. };
  10760. /**
  10761. * Get all child-meshes of this node.
  10762. */
  10763. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10764. var results = [];
  10765. this._getDescendants(results, directDecendantsOnly, function (node) {
  10766. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10767. });
  10768. return results;
  10769. };
  10770. /**
  10771. * Get all direct children of this node.
  10772. */
  10773. Node.prototype.getChildren = function (predicate) {
  10774. return this.getDescendants(true, predicate);
  10775. };
  10776. Node.prototype._setReady = function (state) {
  10777. if (state === this._isReady) {
  10778. return;
  10779. }
  10780. if (!state) {
  10781. this._isReady = false;
  10782. return;
  10783. }
  10784. this._isReady = true;
  10785. if (this.onReady) {
  10786. this.onReady(this);
  10787. }
  10788. };
  10789. Node.prototype.getAnimationByName = function (name) {
  10790. for (var i = 0; i < this.animations.length; i++) {
  10791. var animation = this.animations[i];
  10792. if (animation.name === name) {
  10793. return animation;
  10794. }
  10795. }
  10796. return null;
  10797. };
  10798. Node.prototype.createAnimationRange = function (name, from, to) {
  10799. // check name not already in use
  10800. if (!this._ranges[name]) {
  10801. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10802. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10803. if (this.animations[i]) {
  10804. this.animations[i].createRange(name, from, to);
  10805. }
  10806. }
  10807. }
  10808. };
  10809. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10810. if (deleteFrames === void 0) { deleteFrames = true; }
  10811. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10812. if (this.animations[i]) {
  10813. this.animations[i].deleteRange(name, deleteFrames);
  10814. }
  10815. }
  10816. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10817. };
  10818. Node.prototype.getAnimationRange = function (name) {
  10819. return this._ranges[name];
  10820. };
  10821. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10822. var range = this.getAnimationRange(name);
  10823. if (!range) {
  10824. return null;
  10825. }
  10826. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10827. };
  10828. Node.prototype.serializeAnimationRanges = function () {
  10829. var serializationRanges = [];
  10830. for (var name in this._ranges) {
  10831. var range = {};
  10832. range.name = name;
  10833. range.from = this._ranges[name].from;
  10834. range.to = this._ranges[name].to;
  10835. serializationRanges.push(range);
  10836. }
  10837. return serializationRanges;
  10838. };
  10839. Node.prototype.dispose = function () {
  10840. this.parent = null;
  10841. // Callback
  10842. this.onDisposeObservable.notifyObservers(this);
  10843. this.onDisposeObservable.clear();
  10844. };
  10845. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10846. if (parsedNode.ranges) {
  10847. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10848. var data = parsedNode.ranges[index];
  10849. node.createAnimationRange(data.name, data.from, data.to);
  10850. }
  10851. }
  10852. };
  10853. return Node;
  10854. }());
  10855. __decorate([
  10856. BABYLON.serialize()
  10857. ], Node.prototype, "name", void 0);
  10858. __decorate([
  10859. BABYLON.serialize()
  10860. ], Node.prototype, "id", void 0);
  10861. __decorate([
  10862. BABYLON.serialize()
  10863. ], Node.prototype, "uniqueId", void 0);
  10864. __decorate([
  10865. BABYLON.serialize()
  10866. ], Node.prototype, "state", void 0);
  10867. __decorate([
  10868. BABYLON.serialize()
  10869. ], Node.prototype, "metadata", void 0);
  10870. BABYLON.Node = Node;
  10871. })(BABYLON || (BABYLON = {}));
  10872. //# sourceMappingURL=babylon.node.js.map
  10873. var BABYLON;
  10874. (function (BABYLON) {
  10875. var BoundingSphere = (function () {
  10876. function BoundingSphere(minimum, maximum) {
  10877. this.minimum = minimum;
  10878. this.maximum = maximum;
  10879. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10880. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10881. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10882. this.radius = distance * 0.5;
  10883. this.centerWorld = BABYLON.Vector3.Zero();
  10884. this._update(BABYLON.Matrix.Identity());
  10885. }
  10886. // Methods
  10887. BoundingSphere.prototype._update = function (world) {
  10888. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10889. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10890. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10891. };
  10892. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10893. for (var i = 0; i < 6; i++) {
  10894. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10895. return false;
  10896. }
  10897. return true;
  10898. };
  10899. BoundingSphere.prototype.intersectsPoint = function (point) {
  10900. var x = this.centerWorld.x - point.x;
  10901. var y = this.centerWorld.y - point.y;
  10902. var z = this.centerWorld.z - point.z;
  10903. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10904. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10905. return false;
  10906. return true;
  10907. };
  10908. // Statics
  10909. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10910. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10911. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10912. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10913. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10914. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10915. return false;
  10916. return true;
  10917. };
  10918. return BoundingSphere;
  10919. }());
  10920. BABYLON.BoundingSphere = BoundingSphere;
  10921. })(BABYLON || (BABYLON = {}));
  10922. //# sourceMappingURL=babylon.boundingSphere.js.map
  10923. var BABYLON;
  10924. (function (BABYLON) {
  10925. var BoundingBox = (function () {
  10926. function BoundingBox(minimum, maximum) {
  10927. this.minimum = minimum;
  10928. this.maximum = maximum;
  10929. this.vectors = new Array();
  10930. this.vectorsWorld = new Array();
  10931. // Bounding vectors
  10932. this.vectors.push(this.minimum.clone());
  10933. this.vectors.push(this.maximum.clone());
  10934. this.vectors.push(this.minimum.clone());
  10935. this.vectors[2].x = this.maximum.x;
  10936. this.vectors.push(this.minimum.clone());
  10937. this.vectors[3].y = this.maximum.y;
  10938. this.vectors.push(this.minimum.clone());
  10939. this.vectors[4].z = this.maximum.z;
  10940. this.vectors.push(this.maximum.clone());
  10941. this.vectors[5].z = this.minimum.z;
  10942. this.vectors.push(this.maximum.clone());
  10943. this.vectors[6].x = this.minimum.x;
  10944. this.vectors.push(this.maximum.clone());
  10945. this.vectors[7].y = this.minimum.y;
  10946. // OBB
  10947. this.center = this.maximum.add(this.minimum).scale(0.5);
  10948. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10949. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10950. // World
  10951. for (var index = 0; index < this.vectors.length; index++) {
  10952. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10953. }
  10954. this.minimumWorld = BABYLON.Vector3.Zero();
  10955. this.maximumWorld = BABYLON.Vector3.Zero();
  10956. this.centerWorld = BABYLON.Vector3.Zero();
  10957. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10958. this._update(BABYLON.Matrix.Identity());
  10959. }
  10960. // Methods
  10961. BoundingBox.prototype.getWorldMatrix = function () {
  10962. return this._worldMatrix;
  10963. };
  10964. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10965. this._worldMatrix.copyFrom(matrix);
  10966. return this;
  10967. };
  10968. BoundingBox.prototype._update = function (world) {
  10969. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10970. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10971. for (var index = 0; index < this.vectors.length; index++) {
  10972. var v = this.vectorsWorld[index];
  10973. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10974. if (v.x < this.minimumWorld.x)
  10975. this.minimumWorld.x = v.x;
  10976. if (v.y < this.minimumWorld.y)
  10977. this.minimumWorld.y = v.y;
  10978. if (v.z < this.minimumWorld.z)
  10979. this.minimumWorld.z = v.z;
  10980. if (v.x > this.maximumWorld.x)
  10981. this.maximumWorld.x = v.x;
  10982. if (v.y > this.maximumWorld.y)
  10983. this.maximumWorld.y = v.y;
  10984. if (v.z > this.maximumWorld.z)
  10985. this.maximumWorld.z = v.z;
  10986. }
  10987. // Extend
  10988. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10989. this.extendSizeWorld.scaleInPlace(0.5);
  10990. // OBB
  10991. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10992. this.centerWorld.scaleInPlace(0.5);
  10993. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10994. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10995. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10996. this._worldMatrix = world;
  10997. };
  10998. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10999. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11000. };
  11001. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11002. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11003. };
  11004. BoundingBox.prototype.intersectsPoint = function (point) {
  11005. var delta = -BABYLON.Epsilon;
  11006. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11007. return false;
  11008. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11009. return false;
  11010. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11011. return false;
  11012. return true;
  11013. };
  11014. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11015. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11016. };
  11017. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11018. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11019. return false;
  11020. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11021. return false;
  11022. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11023. return false;
  11024. return true;
  11025. };
  11026. // Statics
  11027. BoundingBox.Intersects = function (box0, box1) {
  11028. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11029. return false;
  11030. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11031. return false;
  11032. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11033. return false;
  11034. return true;
  11035. };
  11036. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11037. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11038. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11039. return (num <= (sphereRadius * sphereRadius));
  11040. };
  11041. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11042. for (var p = 0; p < 6; p++) {
  11043. for (var i = 0; i < 8; i++) {
  11044. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11045. return false;
  11046. }
  11047. }
  11048. }
  11049. return true;
  11050. };
  11051. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11052. for (var p = 0; p < 6; p++) {
  11053. var inCount = 8;
  11054. for (var i = 0; i < 8; i++) {
  11055. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11056. --inCount;
  11057. }
  11058. else {
  11059. break;
  11060. }
  11061. }
  11062. if (inCount === 0)
  11063. return false;
  11064. }
  11065. return true;
  11066. };
  11067. return BoundingBox;
  11068. }());
  11069. BABYLON.BoundingBox = BoundingBox;
  11070. })(BABYLON || (BABYLON = {}));
  11071. //# sourceMappingURL=babylon.boundingBox.js.map
  11072. var BABYLON;
  11073. (function (BABYLON) {
  11074. var computeBoxExtents = function (axis, box) {
  11075. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11076. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11077. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11078. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11079. var r = r0 + r1 + r2;
  11080. return {
  11081. min: p - r,
  11082. max: p + r
  11083. };
  11084. };
  11085. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11086. var axisOverlap = function (axis, box0, box1) {
  11087. var result0 = computeBoxExtents(axis, box0);
  11088. var result1 = computeBoxExtents(axis, box1);
  11089. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11090. };
  11091. var BoundingInfo = (function () {
  11092. function BoundingInfo(minimum, maximum) {
  11093. this.minimum = minimum;
  11094. this.maximum = maximum;
  11095. this._isLocked = false;
  11096. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11097. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11098. }
  11099. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11100. get: function () {
  11101. return this._isLocked;
  11102. },
  11103. set: function (value) {
  11104. this._isLocked = value;
  11105. },
  11106. enumerable: true,
  11107. configurable: true
  11108. });
  11109. // Methods
  11110. BoundingInfo.prototype.update = function (world) {
  11111. if (this._isLocked) {
  11112. return;
  11113. }
  11114. this.boundingBox._update(world);
  11115. this.boundingSphere._update(world);
  11116. };
  11117. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11118. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11119. return false;
  11120. return this.boundingBox.isInFrustum(frustumPlanes);
  11121. };
  11122. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11123. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11124. };
  11125. BoundingInfo.prototype._checkCollision = function (collider) {
  11126. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11127. };
  11128. BoundingInfo.prototype.intersectsPoint = function (point) {
  11129. if (!this.boundingSphere.centerWorld) {
  11130. return false;
  11131. }
  11132. if (!this.boundingSphere.intersectsPoint(point)) {
  11133. return false;
  11134. }
  11135. if (!this.boundingBox.intersectsPoint(point)) {
  11136. return false;
  11137. }
  11138. return true;
  11139. };
  11140. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11141. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11142. return false;
  11143. }
  11144. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11145. return false;
  11146. }
  11147. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11148. return false;
  11149. }
  11150. if (!precise) {
  11151. return true;
  11152. }
  11153. var box0 = this.boundingBox;
  11154. var box1 = boundingInfo.boundingBox;
  11155. if (!axisOverlap(box0.directions[0], box0, box1))
  11156. return false;
  11157. if (!axisOverlap(box0.directions[1], box0, box1))
  11158. return false;
  11159. if (!axisOverlap(box0.directions[2], box0, box1))
  11160. return false;
  11161. if (!axisOverlap(box1.directions[0], box0, box1))
  11162. return false;
  11163. if (!axisOverlap(box1.directions[1], box0, box1))
  11164. return false;
  11165. if (!axisOverlap(box1.directions[2], box0, box1))
  11166. return false;
  11167. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11168. return false;
  11169. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11170. return false;
  11171. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11172. return false;
  11173. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11174. return false;
  11175. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11176. return false;
  11177. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11178. return false;
  11179. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11180. return false;
  11181. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11182. return false;
  11183. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11184. return false;
  11185. return true;
  11186. };
  11187. return BoundingInfo;
  11188. }());
  11189. BABYLON.BoundingInfo = BoundingInfo;
  11190. })(BABYLON || (BABYLON = {}));
  11191. //# sourceMappingURL=babylon.boundingInfo.js.map
  11192. var BABYLON;
  11193. (function (BABYLON) {
  11194. var AbstractMesh = (function (_super) {
  11195. __extends(AbstractMesh, _super);
  11196. // Constructor
  11197. function AbstractMesh(name, scene) {
  11198. var _this = _super.call(this, name, scene) || this;
  11199. _this._facetNb = 0; // facet number
  11200. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11201. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11202. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11203. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11204. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11205. _this._subDiv = {
  11206. max: 1,
  11207. X: 1,
  11208. Y: 1,
  11209. Z: 1
  11210. };
  11211. // Events
  11212. /**
  11213. * An event triggered when this mesh collides with another one
  11214. * @type {BABYLON.Observable}
  11215. */
  11216. _this.onCollideObservable = new BABYLON.Observable();
  11217. /**
  11218. * An event triggered when the collision's position changes
  11219. * @type {BABYLON.Observable}
  11220. */
  11221. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11222. /**
  11223. * An event triggered after the world matrix is updated
  11224. * @type {BABYLON.Observable}
  11225. */
  11226. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11227. // Properties
  11228. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11229. _this.position = BABYLON.Vector3.Zero();
  11230. _this._rotation = BABYLON.Vector3.Zero();
  11231. _this._scaling = BABYLON.Vector3.One();
  11232. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11233. _this.visibility = 1.0;
  11234. _this.alphaIndex = Number.MAX_VALUE;
  11235. _this.infiniteDistance = false;
  11236. _this.isVisible = true;
  11237. _this.isPickable = true;
  11238. _this.showBoundingBox = false;
  11239. _this.showSubMeshesBoundingBox = false;
  11240. _this.isBlocker = false;
  11241. _this.renderingGroupId = 0;
  11242. _this._receiveShadows = false;
  11243. _this.renderOutline = false;
  11244. _this.outlineColor = BABYLON.Color3.Red();
  11245. _this.outlineWidth = 0.02;
  11246. _this.renderOverlay = false;
  11247. _this.overlayColor = BABYLON.Color3.Red();
  11248. _this.overlayAlpha = 0.5;
  11249. _this._hasVertexAlpha = false;
  11250. _this._useVertexColors = true;
  11251. _this._computeBonesUsingShaders = true;
  11252. _this._numBoneInfluencers = 4;
  11253. _this._applyFog = true;
  11254. _this.scalingDeterminant = 1;
  11255. _this.useOctreeForRenderingSelection = true;
  11256. _this.useOctreeForPicking = true;
  11257. _this.useOctreeForCollisions = true;
  11258. _this.layerMask = 0x0FFFFFFF;
  11259. /**
  11260. * True if the mesh must be rendered in any case.
  11261. */
  11262. _this.alwaysSelectAsActiveMesh = false;
  11263. // Collisions
  11264. _this._checkCollisions = false;
  11265. _this._collisionMask = -1;
  11266. _this._collisionGroup = -1;
  11267. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11268. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11269. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11270. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11271. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11272. // Edges
  11273. _this.edgesWidth = 1;
  11274. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11275. // Cache
  11276. _this._localWorld = BABYLON.Matrix.Zero();
  11277. _this._worldMatrix = BABYLON.Matrix.Zero();
  11278. _this._absolutePosition = BABYLON.Vector3.Zero();
  11279. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11280. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11281. _this._isDirty = false;
  11282. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11283. _this._isDisposed = false;
  11284. _this._renderId = 0;
  11285. _this._intersectionsInProgress = new Array();
  11286. _this._isWorldMatrixFrozen = false;
  11287. _this._unIndexed = false;
  11288. _this._lightSources = new Array();
  11289. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11290. if (collidedMesh === void 0) { collidedMesh = null; }
  11291. //TODO move this to the collision coordinator!
  11292. if (_this.getScene().workerCollisions)
  11293. newPosition.multiplyInPlace(_this._collider.radius);
  11294. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11295. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11296. _this.position.addInPlace(_this._diffPositionForCollisions);
  11297. }
  11298. if (collidedMesh) {
  11299. _this.onCollideObservable.notifyObservers(collidedMesh);
  11300. }
  11301. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11302. };
  11303. _this.getScene().addMesh(_this);
  11304. _this._resyncLightSources();
  11305. return _this;
  11306. }
  11307. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11308. get: function () {
  11309. return AbstractMesh._BILLBOARDMODE_NONE;
  11310. },
  11311. enumerable: true,
  11312. configurable: true
  11313. });
  11314. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11315. get: function () {
  11316. return AbstractMesh._BILLBOARDMODE_X;
  11317. },
  11318. enumerable: true,
  11319. configurable: true
  11320. });
  11321. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11322. get: function () {
  11323. return AbstractMesh._BILLBOARDMODE_Y;
  11324. },
  11325. enumerable: true,
  11326. configurable: true
  11327. });
  11328. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11329. get: function () {
  11330. return AbstractMesh._BILLBOARDMODE_Z;
  11331. },
  11332. enumerable: true,
  11333. configurable: true
  11334. });
  11335. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11336. get: function () {
  11337. return AbstractMesh._BILLBOARDMODE_ALL;
  11338. },
  11339. enumerable: true,
  11340. configurable: true
  11341. });
  11342. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11343. /**
  11344. * Read-only : the number of facets in the mesh
  11345. */
  11346. get: function () {
  11347. return this._facetNb;
  11348. },
  11349. enumerable: true,
  11350. configurable: true
  11351. });
  11352. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11353. /**
  11354. * The number (integer) of subdivisions per axis in the partioning space
  11355. */
  11356. get: function () {
  11357. return this._partitioningSubdivisions;
  11358. },
  11359. set: function (nb) {
  11360. this._partitioningSubdivisions = nb;
  11361. },
  11362. enumerable: true,
  11363. configurable: true
  11364. });
  11365. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11366. /**
  11367. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11368. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11369. */
  11370. get: function () {
  11371. return this._partitioningBBoxRatio;
  11372. },
  11373. set: function (ratio) {
  11374. this._partitioningBBoxRatio = ratio;
  11375. },
  11376. enumerable: true,
  11377. configurable: true
  11378. });
  11379. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11380. /**
  11381. * Read-only boolean : is the feature facetData enabled ?
  11382. */
  11383. get: function () {
  11384. return this._facetDataEnabled;
  11385. },
  11386. enumerable: true,
  11387. configurable: true
  11388. });
  11389. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11390. set: function (callback) {
  11391. if (this._onCollideObserver) {
  11392. this.onCollideObservable.remove(this._onCollideObserver);
  11393. }
  11394. this._onCollideObserver = this.onCollideObservable.add(callback);
  11395. },
  11396. enumerable: true,
  11397. configurable: true
  11398. });
  11399. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11400. set: function (callback) {
  11401. if (this._onCollisionPositionChangeObserver) {
  11402. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11403. }
  11404. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11405. },
  11406. enumerable: true,
  11407. configurable: true
  11408. });
  11409. Object.defineProperty(AbstractMesh.prototype, "material", {
  11410. get: function () {
  11411. return this._material;
  11412. },
  11413. set: function (value) {
  11414. if (this._material === value) {
  11415. return;
  11416. }
  11417. this._material = value;
  11418. if (!this.subMeshes) {
  11419. return;
  11420. }
  11421. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11422. var subMesh = _a[_i];
  11423. subMesh.setEffect(null);
  11424. }
  11425. },
  11426. enumerable: true,
  11427. configurable: true
  11428. });
  11429. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11430. get: function () {
  11431. return this._receiveShadows;
  11432. },
  11433. set: function (value) {
  11434. if (this._receiveShadows === value) {
  11435. return;
  11436. }
  11437. this._receiveShadows = value;
  11438. this._markSubMeshesAsLightDirty();
  11439. },
  11440. enumerable: true,
  11441. configurable: true
  11442. });
  11443. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11444. get: function () {
  11445. return this._hasVertexAlpha;
  11446. },
  11447. set: function (value) {
  11448. if (this._hasVertexAlpha === value) {
  11449. return;
  11450. }
  11451. this._hasVertexAlpha = value;
  11452. this._markSubMeshesAsAttributesDirty();
  11453. },
  11454. enumerable: true,
  11455. configurable: true
  11456. });
  11457. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11458. get: function () {
  11459. return this._useVertexColors;
  11460. },
  11461. set: function (value) {
  11462. if (this._useVertexColors === value) {
  11463. return;
  11464. }
  11465. this._useVertexColors = value;
  11466. this._markSubMeshesAsAttributesDirty();
  11467. },
  11468. enumerable: true,
  11469. configurable: true
  11470. });
  11471. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11472. get: function () {
  11473. return this._computeBonesUsingShaders;
  11474. },
  11475. set: function (value) {
  11476. if (this._computeBonesUsingShaders === value) {
  11477. return;
  11478. }
  11479. this._computeBonesUsingShaders = value;
  11480. this._markSubMeshesAsAttributesDirty();
  11481. },
  11482. enumerable: true,
  11483. configurable: true
  11484. });
  11485. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11486. get: function () {
  11487. return this._numBoneInfluencers;
  11488. },
  11489. set: function (value) {
  11490. if (this._numBoneInfluencers === value) {
  11491. return;
  11492. }
  11493. this._numBoneInfluencers = value;
  11494. this._markSubMeshesAsAttributesDirty();
  11495. },
  11496. enumerable: true,
  11497. configurable: true
  11498. });
  11499. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11500. get: function () {
  11501. return this._applyFog;
  11502. },
  11503. set: function (value) {
  11504. if (this._applyFog === value) {
  11505. return;
  11506. }
  11507. this._applyFog = value;
  11508. this._markSubMeshesAsMiscDirty();
  11509. },
  11510. enumerable: true,
  11511. configurable: true
  11512. });
  11513. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11514. get: function () {
  11515. return this._collisionMask;
  11516. },
  11517. set: function (mask) {
  11518. this._collisionMask = !isNaN(mask) ? mask : -1;
  11519. },
  11520. enumerable: true,
  11521. configurable: true
  11522. });
  11523. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11524. get: function () {
  11525. return this._collisionGroup;
  11526. },
  11527. set: function (mask) {
  11528. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11529. },
  11530. enumerable: true,
  11531. configurable: true
  11532. });
  11533. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11534. get: function () {
  11535. return null;
  11536. },
  11537. enumerable: true,
  11538. configurable: true
  11539. });
  11540. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11541. get: function () {
  11542. return this._skeleton;
  11543. },
  11544. set: function (value) {
  11545. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11546. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11547. }
  11548. if (value && value.needInitialSkinMatrix) {
  11549. value._registerMeshWithPoseMatrix(this);
  11550. }
  11551. this._skeleton = value;
  11552. if (!this._skeleton) {
  11553. this._bonesTransformMatrices = null;
  11554. }
  11555. this._markSubMeshesAsAttributesDirty();
  11556. },
  11557. enumerable: true,
  11558. configurable: true
  11559. });
  11560. /**
  11561. * Returns the string "AbstractMesh"
  11562. */
  11563. AbstractMesh.prototype.getClassName = function () {
  11564. return "AbstractMesh";
  11565. };
  11566. /**
  11567. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11568. */
  11569. AbstractMesh.prototype.toString = function (fullDetails) {
  11570. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11571. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11572. if (this._skeleton) {
  11573. ret += ", skeleton: " + this._skeleton.name;
  11574. }
  11575. if (fullDetails) {
  11576. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11577. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11578. }
  11579. return ret;
  11580. };
  11581. AbstractMesh.prototype._resyncLightSources = function () {
  11582. this._lightSources.length = 0;
  11583. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11584. var light = _a[_i];
  11585. if (!light.isEnabled()) {
  11586. continue;
  11587. }
  11588. if (light.canAffectMesh(this)) {
  11589. this._lightSources.push(light);
  11590. }
  11591. }
  11592. this._markSubMeshesAsLightDirty();
  11593. };
  11594. AbstractMesh.prototype._resyncLighSource = function (light) {
  11595. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11596. var index = this._lightSources.indexOf(light);
  11597. if (index === -1) {
  11598. if (!isIn) {
  11599. return;
  11600. }
  11601. this._lightSources.push(light);
  11602. }
  11603. else {
  11604. if (isIn) {
  11605. return;
  11606. }
  11607. this._lightSources.splice(index, 1);
  11608. }
  11609. this._markSubMeshesAsLightDirty();
  11610. };
  11611. AbstractMesh.prototype._removeLightSource = function (light) {
  11612. var index = this._lightSources.indexOf(light);
  11613. if (index === -1) {
  11614. return;
  11615. }
  11616. this._lightSources.splice(index, 1);
  11617. };
  11618. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11619. if (!this.subMeshes) {
  11620. return;
  11621. }
  11622. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11623. var subMesh = _a[_i];
  11624. if (subMesh._materialDefines) {
  11625. func(subMesh._materialDefines);
  11626. }
  11627. }
  11628. };
  11629. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11630. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11631. };
  11632. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11633. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11634. };
  11635. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11636. if (!this.subMeshes) {
  11637. return;
  11638. }
  11639. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11640. var subMesh = _a[_i];
  11641. var material = subMesh.getMaterial();
  11642. if (material) {
  11643. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11644. }
  11645. }
  11646. };
  11647. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11648. /**
  11649. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11650. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11651. * Default : (0.0, 0.0, 0.0)
  11652. */
  11653. get: function () {
  11654. return this._rotation;
  11655. },
  11656. set: function (newRotation) {
  11657. this._rotation = newRotation;
  11658. },
  11659. enumerable: true,
  11660. configurable: true
  11661. });
  11662. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11663. /**
  11664. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11665. * Default : (1.0, 1.0, 1.0)
  11666. */
  11667. get: function () {
  11668. return this._scaling;
  11669. },
  11670. set: function (newScaling) {
  11671. this._scaling = newScaling;
  11672. if (this.physicsImpostor) {
  11673. this.physicsImpostor.forceUpdate();
  11674. }
  11675. },
  11676. enumerable: true,
  11677. configurable: true
  11678. });
  11679. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11680. /**
  11681. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11682. * It's null by default.
  11683. * 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)
  11684. */
  11685. get: function () {
  11686. return this._rotationQuaternion;
  11687. },
  11688. set: function (quaternion) {
  11689. this._rotationQuaternion = quaternion;
  11690. //reset the rotation vector.
  11691. if (quaternion && this.rotation.length()) {
  11692. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11693. }
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. // Methods
  11699. /**
  11700. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11701. * Returns the AbstractMesh.
  11702. */
  11703. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11704. this._poseMatrix.copyFrom(matrix);
  11705. return this;
  11706. };
  11707. /**
  11708. * Returns the mesh Pose matrix.
  11709. * Returned object : Matrix
  11710. */
  11711. AbstractMesh.prototype.getPoseMatrix = function () {
  11712. return this._poseMatrix;
  11713. };
  11714. /**
  11715. * Disables the mesh edger rendering mode.
  11716. * Returns the AbstractMesh.
  11717. */
  11718. AbstractMesh.prototype.disableEdgesRendering = function () {
  11719. if (this._edgesRenderer !== undefined) {
  11720. this._edgesRenderer.dispose();
  11721. this._edgesRenderer = undefined;
  11722. }
  11723. return this;
  11724. };
  11725. /**
  11726. * Enables the edge rendering mode on the mesh.
  11727. * This mode makes the mesh edges visible.
  11728. * Returns the AbstractMesh.
  11729. */
  11730. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11731. if (epsilon === void 0) { epsilon = 0.95; }
  11732. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11733. this.disableEdgesRendering();
  11734. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11735. return this;
  11736. };
  11737. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11738. /**
  11739. * Returns true if the mesh is blocked. Used by the class Mesh.
  11740. * Returns the boolean `false` by default.
  11741. */
  11742. get: function () {
  11743. return false;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. /**
  11749. * Returns the mesh itself by default, used by the class Mesh.
  11750. * Returned type : AbstractMesh
  11751. */
  11752. AbstractMesh.prototype.getLOD = function (camera) {
  11753. return this;
  11754. };
  11755. /**
  11756. * Returns 0 by default, used by the class Mesh.
  11757. * Returns an integer.
  11758. */
  11759. AbstractMesh.prototype.getTotalVertices = function () {
  11760. return 0;
  11761. };
  11762. /**
  11763. * Returns null by default, used by the class Mesh.
  11764. * Returned type : integer array
  11765. */
  11766. AbstractMesh.prototype.getIndices = function () {
  11767. return null;
  11768. };
  11769. /**
  11770. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11771. * Returned type : float array or Float32Array
  11772. */
  11773. AbstractMesh.prototype.getVerticesData = function (kind) {
  11774. return null;
  11775. };
  11776. /**
  11777. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11778. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11779. * The `data` are either a numeric array either a Float32Array.
  11780. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11781. * 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).
  11782. * Note that a new underlying VertexBuffer object is created each call.
  11783. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11784. *
  11785. * Possible `kind` values :
  11786. * - BABYLON.VertexBuffer.PositionKind
  11787. * - BABYLON.VertexBuffer.UVKind
  11788. * - BABYLON.VertexBuffer.UV2Kind
  11789. * - BABYLON.VertexBuffer.UV3Kind
  11790. * - BABYLON.VertexBuffer.UV4Kind
  11791. * - BABYLON.VertexBuffer.UV5Kind
  11792. * - BABYLON.VertexBuffer.UV6Kind
  11793. * - BABYLON.VertexBuffer.ColorKind
  11794. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11795. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11796. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11797. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11798. *
  11799. * Returns the Mesh.
  11800. */
  11801. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11802. return null;
  11803. };
  11804. /**
  11805. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11806. * If the mesh has no geometry, it is simply returned as it is.
  11807. * The `data` are either a numeric array either a Float32Array.
  11808. * No new underlying VertexBuffer object is created.
  11809. * 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.
  11810. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11811. *
  11812. * Possible `kind` values :
  11813. * - BABYLON.VertexBuffer.PositionKind
  11814. * - BABYLON.VertexBuffer.UVKind
  11815. * - BABYLON.VertexBuffer.UV2Kind
  11816. * - BABYLON.VertexBuffer.UV3Kind
  11817. * - BABYLON.VertexBuffer.UV4Kind
  11818. * - BABYLON.VertexBuffer.UV5Kind
  11819. * - BABYLON.VertexBuffer.UV6Kind
  11820. * - BABYLON.VertexBuffer.ColorKind
  11821. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11822. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11823. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11824. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11825. *
  11826. * Returns the Mesh.
  11827. */
  11828. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11829. return null;
  11830. };
  11831. /**
  11832. * Sets the mesh indices.
  11833. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11834. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11835. * This method creates a new index buffer each call.
  11836. * Returns the Mesh.
  11837. */
  11838. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11839. return null;
  11840. };
  11841. /** Returns false by default, used by the class Mesh.
  11842. * Returns a boolean
  11843. */
  11844. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11845. return false;
  11846. };
  11847. /**
  11848. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11849. * Returns a BoundingInfo
  11850. */
  11851. AbstractMesh.prototype.getBoundingInfo = function () {
  11852. if (this._masterMesh) {
  11853. return this._masterMesh.getBoundingInfo();
  11854. }
  11855. if (!this._boundingInfo) {
  11856. this._updateBoundingInfo();
  11857. }
  11858. return this._boundingInfo;
  11859. };
  11860. /**
  11861. * Sets a mesh new object BoundingInfo.
  11862. * Returns the AbstractMesh.
  11863. */
  11864. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11865. this._boundingInfo = boundingInfo;
  11866. return this;
  11867. };
  11868. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11869. get: function () {
  11870. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11871. },
  11872. enumerable: true,
  11873. configurable: true
  11874. });
  11875. AbstractMesh.prototype._preActivate = function () {
  11876. };
  11877. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11878. };
  11879. AbstractMesh.prototype._activate = function (renderId) {
  11880. this._renderId = renderId;
  11881. };
  11882. /**
  11883. * Returns the last update of the World matrix
  11884. * Returns a Matrix.
  11885. */
  11886. AbstractMesh.prototype.getWorldMatrix = function () {
  11887. if (this._masterMesh) {
  11888. return this._masterMesh.getWorldMatrix();
  11889. }
  11890. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11891. this.computeWorldMatrix();
  11892. }
  11893. return this._worldMatrix;
  11894. };
  11895. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11896. /**
  11897. * Returns directly the last state of the mesh World matrix.
  11898. * A Matrix is returned.
  11899. */
  11900. get: function () {
  11901. return this._worldMatrix;
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11907. /**
  11908. * Returns the current mesh absolute position.
  11909. * Retuns a Vector3.
  11910. */
  11911. get: function () {
  11912. return this._absolutePosition;
  11913. },
  11914. enumerable: true,
  11915. configurable: true
  11916. });
  11917. /**
  11918. * Prevents the World matrix to be computed any longer.
  11919. * Returns the AbstractMesh.
  11920. */
  11921. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11922. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11923. this.computeWorldMatrix(true);
  11924. this._isWorldMatrixFrozen = true;
  11925. return this;
  11926. };
  11927. /**
  11928. * Allows back the World matrix computation.
  11929. * Returns the AbstractMesh.
  11930. */
  11931. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11932. this._isWorldMatrixFrozen = false;
  11933. this.computeWorldMatrix(true);
  11934. return this;
  11935. };
  11936. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11937. /**
  11938. * True if the World matrix has been frozen.
  11939. * Returns a boolean.
  11940. */
  11941. get: function () {
  11942. return this._isWorldMatrixFrozen;
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. /**
  11948. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11949. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11950. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11951. * The passed axis is also normalized.
  11952. * Returns the AbstractMesh.
  11953. */
  11954. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11955. axis.normalize();
  11956. if (!this.rotationQuaternion) {
  11957. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11958. this.rotation = BABYLON.Vector3.Zero();
  11959. }
  11960. var rotationQuaternion;
  11961. if (!space || space === BABYLON.Space.LOCAL) {
  11962. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11963. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11964. }
  11965. else {
  11966. if (this.parent) {
  11967. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11968. invertParentWorldMatrix.invert();
  11969. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11970. }
  11971. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11972. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11973. }
  11974. return this;
  11975. };
  11976. /**
  11977. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  11978. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11979. * The passed axis is also normalized.
  11980. * Returns the AbstractMesh.
  11981. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  11982. */
  11983. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  11984. axis.normalize();
  11985. if (!this.rotationQuaternion) {
  11986. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11987. this.rotation.copyFromFloats(0, 0, 0);
  11988. }
  11989. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  11990. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  11991. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  11992. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  11993. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  11994. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  11995. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  11996. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  11997. this.rotationQuaternion.multiplyInPlace(BABYLON.Tmp.Quaternion[0]);
  11998. return this;
  11999. };
  12000. /**
  12001. * Translates the mesh along the axis vector for the passed distance in the given space.
  12002. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12003. * Returns the AbstractMesh.
  12004. */
  12005. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12006. var displacementVector = axis.scale(distance);
  12007. if (!space || space === BABYLON.Space.LOCAL) {
  12008. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12009. this.setPositionWithLocalVector(tempV3);
  12010. }
  12011. else {
  12012. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12013. }
  12014. return this;
  12015. };
  12016. /**
  12017. * Adds a rotation step to the mesh current rotation.
  12018. * x, y, z are Euler angles expressed in radians.
  12019. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12020. * This means this rotation is made in the mesh local space only.
  12021. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12022. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12023. * ```javascript
  12024. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12025. * ```
  12026. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12027. * 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.
  12028. * Returns the AbstractMesh.
  12029. */
  12030. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12031. var rotationQuaternion;
  12032. if (this.rotationQuaternion) {
  12033. rotationQuaternion = this.rotationQuaternion;
  12034. }
  12035. else {
  12036. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12037. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12038. }
  12039. var accumulation = BABYLON.Tmp.Quaternion[0];
  12040. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12041. rotationQuaternion.multiplyInPlace(accumulation);
  12042. if (!this.rotationQuaternion) {
  12043. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12044. }
  12045. return this;
  12046. };
  12047. /**
  12048. * Retuns the mesh absolute position in the World.
  12049. * Returns a Vector3.
  12050. */
  12051. AbstractMesh.prototype.getAbsolutePosition = function () {
  12052. this.computeWorldMatrix();
  12053. return this._absolutePosition;
  12054. };
  12055. /**
  12056. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12057. * Returns the AbstractMesh.
  12058. */
  12059. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12060. if (!absolutePosition) {
  12061. return;
  12062. }
  12063. var absolutePositionX;
  12064. var absolutePositionY;
  12065. var absolutePositionZ;
  12066. if (absolutePosition.x === undefined) {
  12067. if (arguments.length < 3) {
  12068. return;
  12069. }
  12070. absolutePositionX = arguments[0];
  12071. absolutePositionY = arguments[1];
  12072. absolutePositionZ = arguments[2];
  12073. }
  12074. else {
  12075. absolutePositionX = absolutePosition.x;
  12076. absolutePositionY = absolutePosition.y;
  12077. absolutePositionZ = absolutePosition.z;
  12078. }
  12079. if (this.parent) {
  12080. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12081. invertParentWorldMatrix.invert();
  12082. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12083. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12084. }
  12085. else {
  12086. this.position.x = absolutePositionX;
  12087. this.position.y = absolutePositionY;
  12088. this.position.z = absolutePositionZ;
  12089. }
  12090. return this;
  12091. };
  12092. // ================================== Point of View Movement =================================
  12093. /**
  12094. * Perform relative position change from the point of view of behind the front of the mesh.
  12095. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12096. * Supports definition of mesh facing forward or backward.
  12097. * @param {number} amountRight
  12098. * @param {number} amountUp
  12099. * @param {number} amountForward
  12100. *
  12101. * Returns the AbstractMesh.
  12102. */
  12103. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12104. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12105. return this;
  12106. };
  12107. /**
  12108. * Calculate relative position change from the point of view of behind the front of the mesh.
  12109. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12110. * Supports definition of mesh facing forward or backward.
  12111. * @param {number} amountRight
  12112. * @param {number} amountUp
  12113. * @param {number} amountForward
  12114. *
  12115. * Returns a new Vector3.
  12116. */
  12117. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12118. var rotMatrix = new BABYLON.Matrix();
  12119. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12120. rotQuaternion.toRotationMatrix(rotMatrix);
  12121. var translationDelta = BABYLON.Vector3.Zero();
  12122. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12123. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12124. return translationDelta;
  12125. };
  12126. // ================================== Point of View Rotation =================================
  12127. /**
  12128. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12129. * Supports definition of mesh facing forward or backward.
  12130. * @param {number} flipBack
  12131. * @param {number} twirlClockwise
  12132. * @param {number} tiltRight
  12133. *
  12134. * Returns the AbstractMesh.
  12135. */
  12136. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12137. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12138. return this;
  12139. };
  12140. /**
  12141. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12142. * Supports definition of mesh facing forward or backward.
  12143. * @param {number} flipBack
  12144. * @param {number} twirlClockwise
  12145. * @param {number} tiltRight
  12146. *
  12147. * Returns a new Vector3.
  12148. */
  12149. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12150. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12151. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12152. };
  12153. /**
  12154. * Sets a new pivot matrix to the mesh.
  12155. * Returns the AbstractMesh.
  12156. */
  12157. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12158. this._pivotMatrix = matrix;
  12159. this._cache.pivotMatrixUpdated = true;
  12160. return this;
  12161. };
  12162. /**
  12163. * Returns the mesh pivot matrix.
  12164. * Default : Identity.
  12165. * A Matrix is returned.
  12166. */
  12167. AbstractMesh.prototype.getPivotMatrix = function () {
  12168. return this._pivotMatrix;
  12169. };
  12170. AbstractMesh.prototype._isSynchronized = function () {
  12171. if (this._isDirty) {
  12172. return false;
  12173. }
  12174. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12175. return false;
  12176. if (this._cache.pivotMatrixUpdated) {
  12177. return false;
  12178. }
  12179. if (this.infiniteDistance) {
  12180. return false;
  12181. }
  12182. if (!this._cache.position.equals(this.position))
  12183. return false;
  12184. if (this.rotationQuaternion) {
  12185. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12186. return false;
  12187. }
  12188. if (!this._cache.rotation.equals(this.rotation))
  12189. return false;
  12190. if (!this._cache.scaling.equals(this.scaling))
  12191. return false;
  12192. return true;
  12193. };
  12194. AbstractMesh.prototype._initCache = function () {
  12195. _super.prototype._initCache.call(this);
  12196. this._cache.localMatrixUpdated = false;
  12197. this._cache.position = BABYLON.Vector3.Zero();
  12198. this._cache.scaling = BABYLON.Vector3.Zero();
  12199. this._cache.rotation = BABYLON.Vector3.Zero();
  12200. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12201. this._cache.billboardMode = -1;
  12202. };
  12203. AbstractMesh.prototype.markAsDirty = function (property) {
  12204. if (property === "rotation") {
  12205. this.rotationQuaternion = null;
  12206. }
  12207. this._currentRenderId = Number.MAX_VALUE;
  12208. this._isDirty = true;
  12209. return this;
  12210. };
  12211. /**
  12212. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12213. * Returns the AbstractMesh.
  12214. */
  12215. AbstractMesh.prototype._updateBoundingInfo = function () {
  12216. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12217. this._boundingInfo.update(this.worldMatrixFromCache);
  12218. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12219. return this;
  12220. };
  12221. /**
  12222. * Update a mesh's children BoundingInfo objects only.
  12223. * Returns the AbstractMesh.
  12224. */
  12225. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12226. if (!this.subMeshes) {
  12227. return;
  12228. }
  12229. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12230. var subMesh = this.subMeshes[subIndex];
  12231. if (!subMesh.IsGlobal) {
  12232. subMesh.updateBoundingInfo(matrix);
  12233. }
  12234. }
  12235. return this;
  12236. };
  12237. /**
  12238. * Computes the mesh World matrix and returns it.
  12239. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12240. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12241. * If the parameter `force`is set to `true`, the actual computation is done.
  12242. * Returns the mesh World Matrix.
  12243. */
  12244. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12245. if (this._isWorldMatrixFrozen) {
  12246. return this._worldMatrix;
  12247. }
  12248. if (!force && this.isSynchronized(true)) {
  12249. this._currentRenderId = this.getScene().getRenderId();
  12250. return this._worldMatrix;
  12251. }
  12252. this._cache.position.copyFrom(this.position);
  12253. this._cache.scaling.copyFrom(this.scaling);
  12254. this._cache.pivotMatrixUpdated = false;
  12255. this._cache.billboardMode = this.billboardMode;
  12256. this._currentRenderId = this.getScene().getRenderId();
  12257. this._isDirty = false;
  12258. // Scaling
  12259. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12260. // Rotation
  12261. //rotate, if quaternion is set and rotation was used
  12262. if (this.rotationQuaternion) {
  12263. var len = this.rotation.length();
  12264. if (len) {
  12265. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12266. this.rotation.copyFromFloats(0, 0, 0);
  12267. }
  12268. }
  12269. if (this.rotationQuaternion) {
  12270. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12271. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12272. }
  12273. else {
  12274. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12275. this._cache.rotation.copyFrom(this.rotation);
  12276. }
  12277. // Translation
  12278. if (this.infiniteDistance && !this.parent) {
  12279. var camera = this.getScene().activeCamera;
  12280. if (camera) {
  12281. var cameraWorldMatrix = camera.getWorldMatrix();
  12282. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12283. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12284. }
  12285. }
  12286. else {
  12287. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12288. }
  12289. // Composing transformations
  12290. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12291. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12292. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12293. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12294. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12295. // Need to decompose each rotation here
  12296. var currentPosition = BABYLON.Tmp.Vector3[3];
  12297. if (this.parent && this.parent.getWorldMatrix) {
  12298. if (this._meshToBoneReferal) {
  12299. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12300. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12301. }
  12302. else {
  12303. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12304. }
  12305. }
  12306. else {
  12307. currentPosition.copyFrom(this.position);
  12308. }
  12309. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12310. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12311. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12312. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12313. }
  12314. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12315. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12316. }
  12317. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12318. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12319. }
  12320. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12321. }
  12322. else {
  12323. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12324. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12325. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12326. }
  12327. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12328. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12329. }
  12330. // Local world
  12331. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12332. // Parent
  12333. if (this.parent && this.parent.getWorldMatrix) {
  12334. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12335. if (this._meshToBoneReferal) {
  12336. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12337. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12338. }
  12339. else {
  12340. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12341. }
  12342. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12343. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12344. this._worldMatrix.copyFrom(this._localWorld);
  12345. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12346. }
  12347. else {
  12348. if (this._meshToBoneReferal) {
  12349. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12350. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12351. }
  12352. else {
  12353. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12354. }
  12355. }
  12356. this._markSyncedWithParent();
  12357. }
  12358. else {
  12359. this._worldMatrix.copyFrom(this._localWorld);
  12360. }
  12361. // Bounding info
  12362. this._updateBoundingInfo();
  12363. // Absolute position
  12364. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12365. // Callbacks
  12366. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12367. if (!this._poseMatrix) {
  12368. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12369. }
  12370. return this._worldMatrix;
  12371. };
  12372. /**
  12373. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12374. * @param func: callback function to add
  12375. *
  12376. * Returns the AbstractMesh.
  12377. */
  12378. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12379. this.onAfterWorldMatrixUpdateObservable.add(func);
  12380. return this;
  12381. };
  12382. /**
  12383. * Removes a registered callback function.
  12384. * Returns the AbstractMesh.
  12385. */
  12386. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12387. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12388. return this;
  12389. };
  12390. /**
  12391. * Sets the mesh position in its local space.
  12392. * Returns the AbstractMesh.
  12393. */
  12394. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12395. this.computeWorldMatrix();
  12396. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12397. return this;
  12398. };
  12399. /**
  12400. * Returns the mesh position in the local space from the current World matrix values.
  12401. * Returns a new Vector3.
  12402. */
  12403. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12404. this.computeWorldMatrix();
  12405. var invLocalWorldMatrix = this._localWorld.clone();
  12406. invLocalWorldMatrix.invert();
  12407. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12408. };
  12409. /**
  12410. * Translates the mesh along the passed Vector3 in its local space.
  12411. * Returns the AbstractMesh.
  12412. */
  12413. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12414. this.computeWorldMatrix(true);
  12415. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12416. return this;
  12417. };
  12418. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12419. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12420. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12421. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12422. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12423. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12424. /// <returns>Mesh oriented towards targetMesh</returns>
  12425. if (yawCor === void 0) { yawCor = 0; }
  12426. if (pitchCor === void 0) { pitchCor = 0; }
  12427. if (rollCor === void 0) { rollCor = 0; }
  12428. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12429. var dv = AbstractMesh._lookAtVectorCache;
  12430. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12431. targetPoint.subtractToRef(pos, dv);
  12432. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12433. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12434. var pitch = Math.atan2(dv.y, len);
  12435. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12436. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12437. return this;
  12438. };
  12439. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12440. this._meshToBoneReferal = affectedMesh;
  12441. this.parent = bone;
  12442. if (bone.getWorldMatrix().determinant() < 0) {
  12443. this.scalingDeterminant *= -1;
  12444. }
  12445. return this;
  12446. };
  12447. AbstractMesh.prototype.detachFromBone = function () {
  12448. if (this.parent.getWorldMatrix().determinant() < 0) {
  12449. this.scalingDeterminant *= -1;
  12450. }
  12451. this._meshToBoneReferal = null;
  12452. this.parent = null;
  12453. return this;
  12454. };
  12455. /**
  12456. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12457. * A mesh is in the frustum if its bounding box intersects the frustum.
  12458. * Boolean returned.
  12459. */
  12460. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12461. return this._boundingInfo.isInFrustum(frustumPlanes);
  12462. };
  12463. /**
  12464. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12465. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12466. * Boolean returned.
  12467. */
  12468. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12469. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12470. ;
  12471. };
  12472. /**
  12473. * True if the mesh intersects another mesh or a SolidParticle object.
  12474. * 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)
  12475. * Returns a boolean.
  12476. */
  12477. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12478. if (!this._boundingInfo || !mesh._boundingInfo) {
  12479. return false;
  12480. }
  12481. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12482. };
  12483. /**
  12484. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12485. * Returns a boolean.
  12486. */
  12487. AbstractMesh.prototype.intersectsPoint = function (point) {
  12488. if (!this._boundingInfo) {
  12489. return false;
  12490. }
  12491. return this._boundingInfo.intersectsPoint(point);
  12492. };
  12493. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12494. return this.physicsImpostor;
  12495. };
  12496. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12497. if (!camera) {
  12498. camera = this.getScene().activeCamera;
  12499. }
  12500. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12501. };
  12502. /**
  12503. * Returns the distance from the mesh to the active camera.
  12504. * Returns a float.
  12505. */
  12506. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12507. if (!camera) {
  12508. camera = this.getScene().activeCamera;
  12509. }
  12510. return this.absolutePosition.subtract(camera.position).length();
  12511. };
  12512. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12513. if (!this.physicsImpostor) {
  12514. return;
  12515. }
  12516. this.physicsImpostor.applyImpulse(force, contactPoint);
  12517. return this;
  12518. };
  12519. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12520. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12521. return;
  12522. }
  12523. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12524. mainPivot: pivot1,
  12525. connectedPivot: pivot2,
  12526. nativeParams: options
  12527. });
  12528. return this;
  12529. };
  12530. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12531. // Collisions
  12532. /**
  12533. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12534. * Default `false`.
  12535. */
  12536. get: function () {
  12537. return this._checkCollisions;
  12538. },
  12539. set: function (collisionEnabled) {
  12540. this._checkCollisions = collisionEnabled;
  12541. if (this.getScene().workerCollisions) {
  12542. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12543. }
  12544. },
  12545. enumerable: true,
  12546. configurable: true
  12547. });
  12548. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12549. var globalPosition = this.getAbsolutePosition();
  12550. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12551. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12552. if (!this._collider) {
  12553. this._collider = new BABYLON.Collider();
  12554. }
  12555. this._collider.radius = this.ellipsoid;
  12556. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12557. return this;
  12558. };
  12559. // Submeshes octree
  12560. /**
  12561. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12562. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12563. * Returns an Octree of submeshes.
  12564. */
  12565. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12566. if (maxCapacity === void 0) { maxCapacity = 64; }
  12567. if (maxDepth === void 0) { maxDepth = 2; }
  12568. if (!this._submeshesOctree) {
  12569. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12570. }
  12571. this.computeWorldMatrix(true);
  12572. // Update octree
  12573. var bbox = this.getBoundingInfo().boundingBox;
  12574. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12575. return this._submeshesOctree;
  12576. };
  12577. // Collisions
  12578. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12579. this._generatePointsArray();
  12580. // Transformation
  12581. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12582. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12583. subMesh._lastColliderWorldVertices = [];
  12584. subMesh._trianglePlanes = [];
  12585. var start = subMesh.verticesStart;
  12586. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12587. for (var i = start; i < end; i++) {
  12588. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12589. }
  12590. }
  12591. // Collide
  12592. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12593. if (collider.collisionFound) {
  12594. collider.collidedMesh = this;
  12595. }
  12596. return this;
  12597. };
  12598. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12599. var subMeshes;
  12600. var len;
  12601. // Octrees
  12602. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12603. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12604. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12605. len = intersections.length;
  12606. subMeshes = intersections.data;
  12607. }
  12608. else {
  12609. subMeshes = this.subMeshes;
  12610. len = subMeshes.length;
  12611. }
  12612. for (var index = 0; index < len; index++) {
  12613. var subMesh = subMeshes[index];
  12614. // Bounding test
  12615. if (len > 1 && !subMesh._checkCollision(collider))
  12616. continue;
  12617. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12618. }
  12619. return this;
  12620. };
  12621. AbstractMesh.prototype._checkCollision = function (collider) {
  12622. // Bounding box test
  12623. if (!this._boundingInfo._checkCollision(collider))
  12624. return this;
  12625. // Transformation matrix
  12626. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12627. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12628. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12629. return this;
  12630. };
  12631. // Picking
  12632. AbstractMesh.prototype._generatePointsArray = function () {
  12633. return false;
  12634. };
  12635. /**
  12636. * Checks if the passed Ray intersects with the mesh.
  12637. * Returns an object PickingInfo.
  12638. */
  12639. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12640. var pickingInfo = new BABYLON.PickingInfo();
  12641. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12642. return pickingInfo;
  12643. }
  12644. if (!this._generatePointsArray()) {
  12645. return pickingInfo;
  12646. }
  12647. var intersectInfo = null;
  12648. // Octrees
  12649. var subMeshes;
  12650. var len;
  12651. if (this._submeshesOctree && this.useOctreeForPicking) {
  12652. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12653. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12654. len = intersections.length;
  12655. subMeshes = intersections.data;
  12656. }
  12657. else {
  12658. subMeshes = this.subMeshes;
  12659. len = subMeshes.length;
  12660. }
  12661. for (var index = 0; index < len; index++) {
  12662. var subMesh = subMeshes[index];
  12663. // Bounding test
  12664. if (len > 1 && !subMesh.canIntersects(ray))
  12665. continue;
  12666. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12667. if (currentIntersectInfo) {
  12668. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12669. intersectInfo = currentIntersectInfo;
  12670. intersectInfo.subMeshId = index;
  12671. if (fastCheck) {
  12672. break;
  12673. }
  12674. }
  12675. }
  12676. }
  12677. if (intersectInfo) {
  12678. // Get picked point
  12679. var world = this.getWorldMatrix();
  12680. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12681. var direction = ray.direction.clone();
  12682. direction = direction.scale(intersectInfo.distance);
  12683. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12684. var pickedPoint = worldOrigin.add(worldDirection);
  12685. // Return result
  12686. pickingInfo.hit = true;
  12687. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12688. pickingInfo.pickedPoint = pickedPoint;
  12689. pickingInfo.pickedMesh = this;
  12690. pickingInfo.bu = intersectInfo.bu;
  12691. pickingInfo.bv = intersectInfo.bv;
  12692. pickingInfo.faceId = intersectInfo.faceId;
  12693. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12694. return pickingInfo;
  12695. }
  12696. return pickingInfo;
  12697. };
  12698. /**
  12699. * Clones the mesh, used by the class Mesh.
  12700. * Just returns `null` for an AbstractMesh.
  12701. */
  12702. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12703. return null;
  12704. };
  12705. /**
  12706. * Disposes all the mesh submeshes.
  12707. * Returns the AbstractMesh.
  12708. */
  12709. AbstractMesh.prototype.releaseSubMeshes = function () {
  12710. if (this.subMeshes) {
  12711. while (this.subMeshes.length) {
  12712. this.subMeshes[0].dispose();
  12713. }
  12714. }
  12715. else {
  12716. this.subMeshes = new Array();
  12717. }
  12718. return this;
  12719. };
  12720. /**
  12721. * Disposes the AbstractMesh.
  12722. * Some internal references are kept for further use.
  12723. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12724. * Returns nothing.
  12725. */
  12726. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12727. var _this = this;
  12728. var index;
  12729. // Action manager
  12730. if (this.actionManager) {
  12731. this.actionManager.dispose();
  12732. this.actionManager = null;
  12733. }
  12734. // Skeleton
  12735. this.skeleton = null;
  12736. // Animations
  12737. this.getScene().stopAnimation(this);
  12738. // Physics
  12739. if (this.physicsImpostor) {
  12740. this.physicsImpostor.dispose();
  12741. }
  12742. // Intersections in progress
  12743. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12744. var other = this._intersectionsInProgress[index];
  12745. var pos = other._intersectionsInProgress.indexOf(this);
  12746. other._intersectionsInProgress.splice(pos, 1);
  12747. }
  12748. this._intersectionsInProgress = [];
  12749. // Lights
  12750. var lights = this.getScene().lights;
  12751. lights.forEach(function (light) {
  12752. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12753. if (meshIndex !== -1) {
  12754. light.includedOnlyMeshes.splice(meshIndex, 1);
  12755. }
  12756. meshIndex = light.excludedMeshes.indexOf(_this);
  12757. if (meshIndex !== -1) {
  12758. light.excludedMeshes.splice(meshIndex, 1);
  12759. }
  12760. // Shadow generators
  12761. var generator = light.getShadowGenerator();
  12762. if (generator) {
  12763. var shadowMap = generator.getShadowMap();
  12764. meshIndex = shadowMap.renderList.indexOf(_this);
  12765. if (meshIndex !== -1) {
  12766. shadowMap.renderList.splice(meshIndex, 1);
  12767. }
  12768. }
  12769. });
  12770. // Edges
  12771. if (this._edgesRenderer) {
  12772. this._edgesRenderer.dispose();
  12773. this._edgesRenderer = null;
  12774. }
  12775. // SubMeshes
  12776. if (this.getClassName() !== "InstancedMesh") {
  12777. this.releaseSubMeshes();
  12778. }
  12779. // Octree
  12780. var sceneOctree = this.getScene().selectionOctree;
  12781. if (sceneOctree) {
  12782. var index = sceneOctree.dynamicContent.indexOf(this);
  12783. if (index !== -1) {
  12784. sceneOctree.dynamicContent.splice(index, 1);
  12785. }
  12786. }
  12787. // Engine
  12788. this.getScene().getEngine().wipeCaches();
  12789. // Remove from scene
  12790. this.getScene().removeMesh(this);
  12791. if (!doNotRecurse) {
  12792. // Particles
  12793. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12794. if (this.getScene().particleSystems[index].emitter === this) {
  12795. this.getScene().particleSystems[index].dispose();
  12796. index--;
  12797. }
  12798. }
  12799. // Children
  12800. var objects = this.getDescendants(true);
  12801. for (index = 0; index < objects.length; index++) {
  12802. objects[index].dispose();
  12803. }
  12804. }
  12805. else {
  12806. var childMeshes = this.getChildMeshes(true);
  12807. for (index = 0; index < childMeshes.length; index++) {
  12808. var child = childMeshes[index];
  12809. child.parent = null;
  12810. child.computeWorldMatrix(true);
  12811. }
  12812. }
  12813. // facet data
  12814. if (this._facetDataEnabled) {
  12815. this.disableFacetData();
  12816. }
  12817. this.onAfterWorldMatrixUpdateObservable.clear();
  12818. this.onCollideObservable.clear();
  12819. this.onCollisionPositionChangeObservable.clear();
  12820. this._isDisposed = true;
  12821. _super.prototype.dispose.call(this);
  12822. };
  12823. /**
  12824. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12825. * This Vector3 is expressed in the World space.
  12826. */
  12827. AbstractMesh.prototype.getDirection = function (localAxis) {
  12828. var result = BABYLON.Vector3.Zero();
  12829. this.getDirectionToRef(localAxis, result);
  12830. return result;
  12831. };
  12832. /**
  12833. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12834. * localAxis is expressed in the mesh local space.
  12835. * result is computed in the Wordl space from the mesh World matrix.
  12836. * Returns the AbstractMesh.
  12837. */
  12838. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12839. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12840. return this;
  12841. };
  12842. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12843. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12844. if (this.getScene().getRenderId() == 0) {
  12845. this.computeWorldMatrix(true);
  12846. }
  12847. var wm = this.getWorldMatrix();
  12848. if (space == BABYLON.Space.WORLD) {
  12849. var tmat = BABYLON.Tmp.Matrix[0];
  12850. wm.invertToRef(tmat);
  12851. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12852. }
  12853. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12854. this._pivotMatrix.m[12] = -point.x;
  12855. this._pivotMatrix.m[13] = -point.y;
  12856. this._pivotMatrix.m[14] = -point.z;
  12857. this._cache.pivotMatrixUpdated = true;
  12858. return this;
  12859. };
  12860. /**
  12861. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12862. */
  12863. AbstractMesh.prototype.getPivotPoint = function () {
  12864. var point = BABYLON.Vector3.Zero();
  12865. this.getPivotPointToRef(point);
  12866. return point;
  12867. };
  12868. /**
  12869. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12870. * Returns the AbstractMesh.
  12871. */
  12872. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12873. result.x = -this._pivotMatrix.m[12];
  12874. result.y = -this._pivotMatrix.m[13];
  12875. result.z = -this._pivotMatrix.m[14];
  12876. return this;
  12877. };
  12878. /**
  12879. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12880. */
  12881. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12882. var point = BABYLON.Vector3.Zero();
  12883. this.getAbsolutePivotPointToRef(point);
  12884. return point;
  12885. };
  12886. /**
  12887. * Defines the passed mesh as the parent of the current mesh.
  12888. * Returns the AbstractMesh.
  12889. */
  12890. AbstractMesh.prototype.setParent = function (mesh) {
  12891. var child = this;
  12892. var parent = mesh;
  12893. if (mesh == null) {
  12894. var rotation = BABYLON.Tmp.Quaternion[0];
  12895. var position = BABYLON.Tmp.Vector3[0];
  12896. var scale = BABYLON.Tmp.Vector3[1];
  12897. child.getWorldMatrix().decompose(scale, rotation, position);
  12898. if (child.rotationQuaternion) {
  12899. child.rotationQuaternion.copyFrom(rotation);
  12900. }
  12901. else {
  12902. rotation.toEulerAnglesToRef(child.rotation);
  12903. }
  12904. child.position.x = position.x;
  12905. child.position.y = position.y;
  12906. child.position.z = position.z;
  12907. }
  12908. else {
  12909. var rotation = BABYLON.Tmp.Quaternion[0];
  12910. var position = BABYLON.Tmp.Vector3[0];
  12911. var scale = BABYLON.Tmp.Vector3[1];
  12912. var m1 = BABYLON.Tmp.Matrix[0];
  12913. var m2 = BABYLON.Tmp.Matrix[1];
  12914. parent.getWorldMatrix().decompose(scale, rotation, position);
  12915. rotation.toRotationMatrix(m1);
  12916. m2.setTranslation(position);
  12917. m2.multiplyToRef(m1, m1);
  12918. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12919. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12920. m.decompose(scale, rotation, position);
  12921. if (child.rotationQuaternion) {
  12922. child.rotationQuaternion.copyFrom(rotation);
  12923. }
  12924. else {
  12925. rotation.toEulerAnglesToRef(child.rotation);
  12926. }
  12927. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12928. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12929. m.decompose(scale, rotation, position);
  12930. child.position.x = position.x;
  12931. child.position.y = position.y;
  12932. child.position.z = position.z;
  12933. }
  12934. child.parent = parent;
  12935. return this;
  12936. };
  12937. /**
  12938. * Adds the passed mesh as a child to the current mesh.
  12939. * Returns the AbstractMesh.
  12940. */
  12941. AbstractMesh.prototype.addChild = function (mesh) {
  12942. mesh.setParent(this);
  12943. return this;
  12944. };
  12945. /**
  12946. * Removes the passed mesh from the current mesh children list.
  12947. * Returns the AbstractMesh.
  12948. */
  12949. AbstractMesh.prototype.removeChild = function (mesh) {
  12950. mesh.setParent(null);
  12951. return this;
  12952. };
  12953. /**
  12954. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12955. * Returns the AbstractMesh.
  12956. */
  12957. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12958. result.x = this._pivotMatrix.m[12];
  12959. result.y = this._pivotMatrix.m[13];
  12960. result.z = this._pivotMatrix.m[14];
  12961. this.getPivotPointToRef(result);
  12962. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12963. return this;
  12964. };
  12965. // Facet data
  12966. /**
  12967. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12968. * Returns the AbstractMesh.
  12969. */
  12970. AbstractMesh.prototype._initFacetData = function () {
  12971. if (!this._facetNormals) {
  12972. this._facetNormals = new Array();
  12973. }
  12974. if (!this._facetPositions) {
  12975. this._facetPositions = new Array();
  12976. }
  12977. if (!this._facetPartitioning) {
  12978. this._facetPartitioning = new Array();
  12979. }
  12980. this._facetNb = this.getIndices().length / 3;
  12981. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12982. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12983. for (var f = 0; f < this._facetNb; f++) {
  12984. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12985. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12986. }
  12987. this._facetDataEnabled = true;
  12988. return this;
  12989. };
  12990. /**
  12991. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12992. * This method can be called within the render loop.
  12993. * 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.
  12994. * Returns the AbstractMesh.
  12995. */
  12996. AbstractMesh.prototype.updateFacetData = function () {
  12997. if (!this._facetDataEnabled) {
  12998. this._initFacetData();
  12999. }
  13000. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13001. var indices = this.getIndices();
  13002. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13003. var bInfo = this.getBoundingInfo();
  13004. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13005. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13006. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13007. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13008. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13009. this._subDiv.max = this._partitioningSubdivisions;
  13010. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13011. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13012. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13013. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13014. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13015. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13016. // set the parameters for ComputeNormals()
  13017. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13018. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13019. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13020. this._facetParameters.bInfo = bInfo;
  13021. this._facetParameters.bbSize = this._bbSize;
  13022. this._facetParameters.subDiv = this._subDiv;
  13023. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13024. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13025. return this;
  13026. };
  13027. /**
  13028. * Returns the facetLocalNormals array.
  13029. * The normals are expressed in the mesh local space.
  13030. */
  13031. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13032. if (!this._facetNormals) {
  13033. this.updateFacetData();
  13034. }
  13035. return this._facetNormals;
  13036. };
  13037. /**
  13038. * Returns the facetLocalPositions array.
  13039. * The facet positions are expressed in the mesh local space.
  13040. */
  13041. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13042. if (!this._facetPositions) {
  13043. this.updateFacetData();
  13044. }
  13045. return this._facetPositions;
  13046. };
  13047. /**
  13048. * Returns the facetLocalPartioning array.
  13049. */
  13050. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13051. if (!this._facetPartitioning) {
  13052. this.updateFacetData();
  13053. }
  13054. return this._facetPartitioning;
  13055. };
  13056. /**
  13057. * Returns the i-th facet position in the world system.
  13058. * This method allocates a new Vector3 per call.
  13059. */
  13060. AbstractMesh.prototype.getFacetPosition = function (i) {
  13061. var pos = BABYLON.Vector3.Zero();
  13062. this.getFacetPositionToRef(i, pos);
  13063. return pos;
  13064. };
  13065. /**
  13066. * Sets the reference Vector3 with the i-th facet position in the world system.
  13067. * Returns the AbstractMesh.
  13068. */
  13069. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13070. var localPos = (this.getFacetLocalPositions())[i];
  13071. var world = this.getWorldMatrix();
  13072. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13073. return this;
  13074. };
  13075. /**
  13076. * Returns the i-th facet normal in the world system.
  13077. * This method allocates a new Vector3 per call.
  13078. */
  13079. AbstractMesh.prototype.getFacetNormal = function (i) {
  13080. var norm = BABYLON.Vector3.Zero();
  13081. this.getFacetNormalToRef(i, norm);
  13082. return norm;
  13083. };
  13084. /**
  13085. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13086. * Returns the AbstractMesh.
  13087. */
  13088. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13089. var localNorm = (this.getFacetLocalNormals())[i];
  13090. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13091. return this;
  13092. };
  13093. /**
  13094. * 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).
  13095. */
  13096. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13097. var bInfo = this.getBoundingInfo();
  13098. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13099. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13100. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13101. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13102. return null;
  13103. }
  13104. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13105. };
  13106. /**
  13107. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13108. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13109. * 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.
  13110. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13111. * 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.
  13112. */
  13113. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13114. if (checkFace === void 0) { checkFace = false; }
  13115. if (facing === void 0) { facing = true; }
  13116. var world = this.getWorldMatrix();
  13117. var invMat = BABYLON.Tmp.Matrix[5];
  13118. world.invertToRef(invMat);
  13119. var invVect = BABYLON.Tmp.Vector3[8];
  13120. var closest = null;
  13121. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13122. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13123. if (projected) {
  13124. // tranform the local computed projected vector to world coordinates
  13125. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13126. }
  13127. return closest;
  13128. };
  13129. /**
  13130. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13131. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13132. * 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.
  13133. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13134. * 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.
  13135. */
  13136. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13137. if (checkFace === void 0) { checkFace = false; }
  13138. if (facing === void 0) { facing = true; }
  13139. var closest = null;
  13140. var tmpx = 0.0;
  13141. var tmpy = 0.0;
  13142. var tmpz = 0.0;
  13143. var d = 0.0; // tmp dot facet normal * facet position
  13144. var t0 = 0.0;
  13145. var projx = 0.0;
  13146. var projy = 0.0;
  13147. var projz = 0.0;
  13148. // Get all the facets in the same partitioning block than (x, y, z)
  13149. var facetPositions = this.getFacetLocalPositions();
  13150. var facetNormals = this.getFacetLocalNormals();
  13151. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13152. if (!facetsInBlock) {
  13153. return null;
  13154. }
  13155. // Get the closest facet to (x, y, z)
  13156. var shortest = Number.MAX_VALUE; // init distance vars
  13157. var tmpDistance = shortest;
  13158. var fib; // current facet in the block
  13159. var norm; // current facet normal
  13160. var p0; // current facet barycenter position
  13161. // loop on all the facets in the current partitioning block
  13162. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13163. fib = facetsInBlock[idx];
  13164. norm = facetNormals[fib];
  13165. p0 = facetPositions[fib];
  13166. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13167. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13168. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13169. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13170. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13171. projx = x + norm.x * t0;
  13172. projy = y + norm.y * t0;
  13173. projz = z + norm.z * t0;
  13174. tmpx = projx - x;
  13175. tmpy = projy - y;
  13176. tmpz = projz - z;
  13177. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13178. if (tmpDistance < shortest) {
  13179. shortest = tmpDistance;
  13180. closest = fib;
  13181. if (projected) {
  13182. projected.x = projx;
  13183. projected.y = projy;
  13184. projected.z = projz;
  13185. }
  13186. }
  13187. }
  13188. }
  13189. return closest;
  13190. };
  13191. /**
  13192. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13193. */
  13194. AbstractMesh.prototype.getFacetDataParameters = function () {
  13195. return this._facetParameters;
  13196. };
  13197. /**
  13198. * Disables the feature FacetData and frees the related memory.
  13199. * Returns the AbstractMesh.
  13200. */
  13201. AbstractMesh.prototype.disableFacetData = function () {
  13202. if (this._facetDataEnabled) {
  13203. this._facetDataEnabled = false;
  13204. this._facetPositions = null;
  13205. this._facetNormals = null;
  13206. this._facetPartitioning = null;
  13207. this._facetParameters = null;
  13208. }
  13209. return this;
  13210. };
  13211. /**
  13212. * Creates new normals data for the mesh.
  13213. * @param updatable.
  13214. */
  13215. AbstractMesh.prototype.createNormals = function (updatable) {
  13216. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13217. var indices = this.getIndices();
  13218. var normals;
  13219. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13220. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13221. }
  13222. else {
  13223. normals = [];
  13224. }
  13225. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13226. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13227. };
  13228. return AbstractMesh;
  13229. }(BABYLON.Node));
  13230. // Statics
  13231. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13232. AbstractMesh._BILLBOARDMODE_X = 1;
  13233. AbstractMesh._BILLBOARDMODE_Y = 2;
  13234. AbstractMesh._BILLBOARDMODE_Z = 4;
  13235. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13236. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13237. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13238. BABYLON.AbstractMesh = AbstractMesh;
  13239. })(BABYLON || (BABYLON = {}));
  13240. //# sourceMappingURL=babylon.abstractMesh.js.map
  13241. var BABYLON;
  13242. (function (BABYLON) {
  13243. var Light = (function (_super) {
  13244. __extends(Light, _super);
  13245. /**
  13246. * Creates a Light object in the scene.
  13247. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13248. */
  13249. function Light(name, scene) {
  13250. var _this = _super.call(this, name, scene) || this;
  13251. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13252. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13253. _this.intensity = 1.0;
  13254. _this.range = Number.MAX_VALUE;
  13255. /**
  13256. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13257. * of light.
  13258. */
  13259. _this._photometricScale = 1.0;
  13260. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13261. _this._radius = 0.00001;
  13262. _this.renderPriority = 0;
  13263. /**
  13264. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13265. * the current shadow generator.
  13266. */
  13267. _this.shadowEnabled = true;
  13268. _this._excludeWithLayerMask = 0;
  13269. _this._includeOnlyWithLayerMask = 0;
  13270. _this._lightmapMode = 0;
  13271. _this._excludedMeshesIds = new Array();
  13272. _this._includedOnlyMeshesIds = new Array();
  13273. _this.getScene().addLight(_this);
  13274. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13275. _this._buildUniformLayout();
  13276. _this.includedOnlyMeshes = new Array();
  13277. _this.excludedMeshes = new Array();
  13278. _this._resyncMeshes();
  13279. return _this;
  13280. }
  13281. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13282. /**
  13283. * If every light affecting the material is in this lightmapMode,
  13284. * material.lightmapTexture adds or multiplies
  13285. * (depends on material.useLightmapAsShadowmap)
  13286. * after every other light calculations.
  13287. */
  13288. get: function () {
  13289. return Light._LIGHTMAP_DEFAULT;
  13290. },
  13291. enumerable: true,
  13292. configurable: true
  13293. });
  13294. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13295. /**
  13296. * material.lightmapTexture as only diffuse lighting from this light
  13297. * adds pnly specular lighting from this light
  13298. * adds dynamic shadows
  13299. */
  13300. get: function () {
  13301. return Light._LIGHTMAP_SPECULAR;
  13302. },
  13303. enumerable: true,
  13304. configurable: true
  13305. });
  13306. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13307. /**
  13308. * material.lightmapTexture as only lighting
  13309. * no light calculation from this light
  13310. * only adds dynamic shadows from this light
  13311. */
  13312. get: function () {
  13313. return Light._LIGHTMAP_SHADOWSONLY;
  13314. },
  13315. enumerable: true,
  13316. configurable: true
  13317. });
  13318. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13319. /**
  13320. * Each light type uses the default quantity according to its type:
  13321. * point/spot lights use luminous intensity
  13322. * directional lights use illuminance
  13323. */
  13324. get: function () {
  13325. return Light._INTENSITYMODE_AUTOMATIC;
  13326. },
  13327. enumerable: true,
  13328. configurable: true
  13329. });
  13330. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13331. /**
  13332. * lumen (lm)
  13333. */
  13334. get: function () {
  13335. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13336. },
  13337. enumerable: true,
  13338. configurable: true
  13339. });
  13340. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13341. /**
  13342. * candela (lm/sr)
  13343. */
  13344. get: function () {
  13345. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13346. },
  13347. enumerable: true,
  13348. configurable: true
  13349. });
  13350. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13351. /**
  13352. * lux (lm/m^2)
  13353. */
  13354. get: function () {
  13355. return Light._INTENSITYMODE_ILLUMINANCE;
  13356. },
  13357. enumerable: true,
  13358. configurable: true
  13359. });
  13360. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13361. /**
  13362. * nit (cd/m^2)
  13363. */
  13364. get: function () {
  13365. return Light._INTENSITYMODE_LUMINANCE;
  13366. },
  13367. enumerable: true,
  13368. configurable: true
  13369. });
  13370. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13371. /**
  13372. * Light type const id of the point light.
  13373. */
  13374. get: function () {
  13375. return Light._LIGHTTYPEID_POINTLIGHT;
  13376. },
  13377. enumerable: true,
  13378. configurable: true
  13379. });
  13380. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13381. /**
  13382. * Light type const id of the directional light.
  13383. */
  13384. get: function () {
  13385. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13386. },
  13387. enumerable: true,
  13388. configurable: true
  13389. });
  13390. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13391. /**
  13392. * Light type const id of the spot light.
  13393. */
  13394. get: function () {
  13395. return Light._LIGHTTYPEID_SPOTLIGHT;
  13396. },
  13397. enumerable: true,
  13398. configurable: true
  13399. });
  13400. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13401. /**
  13402. * Light type const id of the hemispheric light.
  13403. */
  13404. get: function () {
  13405. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13406. },
  13407. enumerable: true,
  13408. configurable: true
  13409. });
  13410. Object.defineProperty(Light.prototype, "intensityMode", {
  13411. /**
  13412. * Gets the photometric scale used to interpret the intensity.
  13413. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13414. */
  13415. get: function () {
  13416. return this._intensityMode;
  13417. },
  13418. /**
  13419. * Sets the photometric scale used to interpret the intensity.
  13420. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13421. */
  13422. set: function (value) {
  13423. this._intensityMode = value;
  13424. this._computePhotometricScale();
  13425. },
  13426. enumerable: true,
  13427. configurable: true
  13428. });
  13429. ;
  13430. ;
  13431. Object.defineProperty(Light.prototype, "radius", {
  13432. /**
  13433. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13434. */
  13435. get: function () {
  13436. return this._radius;
  13437. },
  13438. /**
  13439. * sets the light radius used by PBR Materials to simulate soft area lights.
  13440. */
  13441. set: function (value) {
  13442. this._radius = value;
  13443. this._computePhotometricScale();
  13444. },
  13445. enumerable: true,
  13446. configurable: true
  13447. });
  13448. ;
  13449. ;
  13450. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13451. get: function () {
  13452. return this._includedOnlyMeshes;
  13453. },
  13454. set: function (value) {
  13455. this._includedOnlyMeshes = value;
  13456. this._hookArrayForIncludedOnly(value);
  13457. },
  13458. enumerable: true,
  13459. configurable: true
  13460. });
  13461. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13462. get: function () {
  13463. return this._excludedMeshes;
  13464. },
  13465. set: function (value) {
  13466. this._excludedMeshes = value;
  13467. this._hookArrayForExcluded(value);
  13468. },
  13469. enumerable: true,
  13470. configurable: true
  13471. });
  13472. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13473. get: function () {
  13474. return this._excludeWithLayerMask;
  13475. },
  13476. set: function (value) {
  13477. this._excludeWithLayerMask = value;
  13478. this._resyncMeshes();
  13479. },
  13480. enumerable: true,
  13481. configurable: true
  13482. });
  13483. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13484. get: function () {
  13485. return this._includeOnlyWithLayerMask;
  13486. },
  13487. set: function (value) {
  13488. this._includeOnlyWithLayerMask = value;
  13489. this._resyncMeshes();
  13490. },
  13491. enumerable: true,
  13492. configurable: true
  13493. });
  13494. Object.defineProperty(Light.prototype, "lightmapMode", {
  13495. get: function () {
  13496. return this._lightmapMode;
  13497. },
  13498. set: function (value) {
  13499. if (this._lightmapMode === value) {
  13500. return;
  13501. }
  13502. this._lightmapMode = value;
  13503. this._markMeshesAsLightDirty();
  13504. },
  13505. enumerable: true,
  13506. configurable: true
  13507. });
  13508. Light.prototype._buildUniformLayout = function () {
  13509. // Overridden
  13510. };
  13511. /**
  13512. * Returns the string "Light".
  13513. */
  13514. Light.prototype.getClassName = function () {
  13515. return "Light";
  13516. };
  13517. /**
  13518. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13519. */
  13520. Light.prototype.toString = function (fullDetails) {
  13521. var ret = "Name: " + this.name;
  13522. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13523. if (this.animations) {
  13524. for (var i = 0; i < this.animations.length; i++) {
  13525. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13526. }
  13527. }
  13528. if (fullDetails) {
  13529. }
  13530. return ret;
  13531. };
  13532. /**
  13533. * Set the enabled state of this node.
  13534. * @param {boolean} value - the new enabled state
  13535. * @see isEnabled
  13536. */
  13537. Light.prototype.setEnabled = function (value) {
  13538. _super.prototype.setEnabled.call(this, value);
  13539. this._resyncMeshes();
  13540. };
  13541. /**
  13542. * Returns the Light associated shadow generator.
  13543. */
  13544. Light.prototype.getShadowGenerator = function () {
  13545. return this._shadowGenerator;
  13546. };
  13547. /**
  13548. * Returns a Vector3, the absolute light position in the World.
  13549. */
  13550. Light.prototype.getAbsolutePosition = function () {
  13551. return BABYLON.Vector3.Zero();
  13552. };
  13553. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13554. };
  13555. Light.prototype._getWorldMatrix = function () {
  13556. return BABYLON.Matrix.Identity();
  13557. };
  13558. /**
  13559. * Boolean : True if the light will affect the passed mesh.
  13560. */
  13561. Light.prototype.canAffectMesh = function (mesh) {
  13562. if (!mesh) {
  13563. return true;
  13564. }
  13565. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13566. return false;
  13567. }
  13568. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13569. return false;
  13570. }
  13571. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13572. return false;
  13573. }
  13574. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13575. return false;
  13576. }
  13577. return true;
  13578. };
  13579. /**
  13580. * Returns the light World matrix.
  13581. */
  13582. Light.prototype.getWorldMatrix = function () {
  13583. this._currentRenderId = this.getScene().getRenderId();
  13584. var worldMatrix = this._getWorldMatrix();
  13585. if (this.parent && this.parent.getWorldMatrix) {
  13586. if (!this._parentedWorldMatrix) {
  13587. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13588. }
  13589. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13590. this._markSyncedWithParent();
  13591. return this._parentedWorldMatrix;
  13592. }
  13593. return worldMatrix;
  13594. };
  13595. /**
  13596. * Sort function to order lights for rendering.
  13597. * @param a First Light object to compare to second.
  13598. * @param b Second Light object to compare first.
  13599. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13600. */
  13601. Light.compareLightsPriority = function (a, b) {
  13602. //shadow-casting lights have priority over non-shadow-casting lights
  13603. //the renderPrioirty is a secondary sort criterion
  13604. if (a.shadowEnabled !== b.shadowEnabled) {
  13605. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13606. }
  13607. return b.renderPriority - a.renderPriority;
  13608. };
  13609. /**
  13610. * Disposes the light.
  13611. */
  13612. Light.prototype.dispose = function () {
  13613. if (this._shadowGenerator) {
  13614. this._shadowGenerator.dispose();
  13615. this._shadowGenerator = null;
  13616. }
  13617. // Animations
  13618. this.getScene().stopAnimation(this);
  13619. // Remove from meshes
  13620. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13621. var mesh = _a[_i];
  13622. mesh._removeLightSource(this);
  13623. }
  13624. this._uniformBuffer.dispose();
  13625. // Remove from scene
  13626. this.getScene().removeLight(this);
  13627. _super.prototype.dispose.call(this);
  13628. };
  13629. /**
  13630. * Returns the light type ID (integer).
  13631. */
  13632. Light.prototype.getTypeID = function () {
  13633. return 0;
  13634. };
  13635. /**
  13636. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13637. */
  13638. Light.prototype.getScaledIntensity = function () {
  13639. return this._photometricScale * this.intensity;
  13640. };
  13641. /**
  13642. * Returns a new Light object, named "name", from the current one.
  13643. */
  13644. Light.prototype.clone = function (name) {
  13645. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13646. };
  13647. /**
  13648. * Serializes the current light into a Serialization object.
  13649. * Returns the serialized object.
  13650. */
  13651. Light.prototype.serialize = function () {
  13652. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13653. // Type
  13654. serializationObject.type = this.getTypeID();
  13655. // Parent
  13656. if (this.parent) {
  13657. serializationObject.parentId = this.parent.id;
  13658. }
  13659. // Inclusion / exclusions
  13660. if (this.excludedMeshes.length > 0) {
  13661. serializationObject.excludedMeshesIds = [];
  13662. this.excludedMeshes.forEach(function (mesh) {
  13663. serializationObject.excludedMeshesIds.push(mesh.id);
  13664. });
  13665. }
  13666. if (this.includedOnlyMeshes.length > 0) {
  13667. serializationObject.includedOnlyMeshesIds = [];
  13668. this.includedOnlyMeshes.forEach(function (mesh) {
  13669. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13670. });
  13671. }
  13672. // Animations
  13673. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13674. serializationObject.ranges = this.serializeAnimationRanges();
  13675. return serializationObject;
  13676. };
  13677. /**
  13678. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13679. * This new light is named "name" and added to the passed scene.
  13680. */
  13681. Light.GetConstructorFromName = function (type, name, scene) {
  13682. switch (type) {
  13683. case 0:
  13684. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13685. case 1:
  13686. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13687. case 2:
  13688. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13689. case 3:
  13690. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13691. }
  13692. };
  13693. /**
  13694. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13695. */
  13696. Light.Parse = function (parsedLight, scene) {
  13697. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13698. // Inclusion / exclusions
  13699. if (parsedLight.excludedMeshesIds) {
  13700. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13701. }
  13702. if (parsedLight.includedOnlyMeshesIds) {
  13703. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13704. }
  13705. // Parent
  13706. if (parsedLight.parentId) {
  13707. light._waitingParentId = parsedLight.parentId;
  13708. }
  13709. // Animations
  13710. if (parsedLight.animations) {
  13711. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13712. var parsedAnimation = parsedLight.animations[animationIndex];
  13713. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13714. }
  13715. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13716. }
  13717. if (parsedLight.autoAnimate) {
  13718. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13719. }
  13720. return light;
  13721. };
  13722. Light.prototype._hookArrayForExcluded = function (array) {
  13723. var _this = this;
  13724. var oldPush = array.push;
  13725. array.push = function () {
  13726. var items = [];
  13727. for (var _i = 0; _i < arguments.length; _i++) {
  13728. items[_i] = arguments[_i];
  13729. }
  13730. var result = oldPush.apply(array, items);
  13731. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13732. var item = items_1[_a];
  13733. item._resyncLighSource(_this);
  13734. }
  13735. return result;
  13736. };
  13737. var oldSplice = array.splice;
  13738. array.splice = function (index, deleteCount) {
  13739. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13740. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13741. var item = deleted_1[_i];
  13742. item._resyncLighSource(_this);
  13743. }
  13744. return deleted;
  13745. };
  13746. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13747. var item = array_1[_i];
  13748. item._resyncLighSource(this);
  13749. }
  13750. };
  13751. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13752. var _this = this;
  13753. var oldPush = array.push;
  13754. array.push = function () {
  13755. var items = [];
  13756. for (var _i = 0; _i < arguments.length; _i++) {
  13757. items[_i] = arguments[_i];
  13758. }
  13759. var result = oldPush.apply(array, items);
  13760. _this._resyncMeshes();
  13761. return result;
  13762. };
  13763. var oldSplice = array.splice;
  13764. array.splice = function (index, deleteCount) {
  13765. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13766. _this._resyncMeshes();
  13767. return deleted;
  13768. };
  13769. this._resyncMeshes();
  13770. };
  13771. Light.prototype._resyncMeshes = function () {
  13772. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13773. var mesh = _a[_i];
  13774. mesh._resyncLighSource(this);
  13775. }
  13776. };
  13777. Light.prototype._markMeshesAsLightDirty = function () {
  13778. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13779. var mesh = _a[_i];
  13780. if (mesh._lightSources.indexOf(this) !== -1) {
  13781. mesh._markSubMeshesAsLightDirty();
  13782. }
  13783. }
  13784. };
  13785. /**
  13786. * Recomputes the cached photometric scale if needed.
  13787. */
  13788. Light.prototype._computePhotometricScale = function () {
  13789. this._photometricScale = this._getPhotometricScale();
  13790. this.getScene().resetCachedMaterial();
  13791. };
  13792. /**
  13793. * Returns the Photometric Scale according to the light type and intensity mode.
  13794. */
  13795. Light.prototype._getPhotometricScale = function () {
  13796. var photometricScale = 0.0;
  13797. var lightTypeID = this.getTypeID();
  13798. //get photometric mode
  13799. var photometricMode = this.intensityMode;
  13800. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13801. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13802. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13803. }
  13804. else {
  13805. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13806. }
  13807. }
  13808. //compute photometric scale
  13809. switch (lightTypeID) {
  13810. case Light.LIGHTTYPEID_POINTLIGHT:
  13811. case Light.LIGHTTYPEID_SPOTLIGHT:
  13812. switch (photometricMode) {
  13813. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13814. photometricScale = 1.0 / (4.0 * Math.PI);
  13815. break;
  13816. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13817. photometricScale = 1.0;
  13818. break;
  13819. case Light.INTENSITYMODE_LUMINANCE:
  13820. photometricScale = this.radius * this.radius;
  13821. break;
  13822. }
  13823. break;
  13824. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13825. switch (photometricMode) {
  13826. case Light.INTENSITYMODE_ILLUMINANCE:
  13827. photometricScale = 1.0;
  13828. break;
  13829. case Light.INTENSITYMODE_LUMINANCE:
  13830. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13831. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13832. var apexAngleRadians = this.radius;
  13833. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13834. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13835. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13836. photometricScale = solidAngle;
  13837. break;
  13838. }
  13839. break;
  13840. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13841. // No fall off in hemisperic light.
  13842. photometricScale = 1.0;
  13843. break;
  13844. }
  13845. return photometricScale;
  13846. };
  13847. Light.prototype._reorderLightsInScene = function () {
  13848. var scene = this.getScene();
  13849. if (this.renderPriority != 0) {
  13850. scene.requireLightSorting = true;
  13851. }
  13852. this.getScene().sortLightsByPriority();
  13853. };
  13854. return Light;
  13855. }(BABYLON.Node));
  13856. //lightmapMode Consts
  13857. Light._LIGHTMAP_DEFAULT = 0;
  13858. Light._LIGHTMAP_SPECULAR = 1;
  13859. Light._LIGHTMAP_SHADOWSONLY = 2;
  13860. // Intensity Mode Consts
  13861. Light._INTENSITYMODE_AUTOMATIC = 0;
  13862. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13863. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13864. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13865. Light._INTENSITYMODE_LUMINANCE = 4;
  13866. // Light types ids const.
  13867. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13868. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13869. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13870. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13871. __decorate([
  13872. BABYLON.serializeAsColor3()
  13873. ], Light.prototype, "diffuse", void 0);
  13874. __decorate([
  13875. BABYLON.serializeAsColor3()
  13876. ], Light.prototype, "specular", void 0);
  13877. __decorate([
  13878. BABYLON.serialize()
  13879. ], Light.prototype, "intensity", void 0);
  13880. __decorate([
  13881. BABYLON.serialize()
  13882. ], Light.prototype, "range", void 0);
  13883. __decorate([
  13884. BABYLON.serialize()
  13885. ], Light.prototype, "intensityMode", null);
  13886. __decorate([
  13887. BABYLON.serialize()
  13888. ], Light.prototype, "radius", null);
  13889. __decorate([
  13890. BABYLON.serialize()
  13891. ], Light.prototype, "_renderPriority", void 0);
  13892. __decorate([
  13893. BABYLON.expandToProperty("_reorderLightsInScene")
  13894. ], Light.prototype, "renderPriority", void 0);
  13895. __decorate([
  13896. BABYLON.serialize()
  13897. ], Light.prototype, "shadowEnabled", void 0);
  13898. __decorate([
  13899. BABYLON.serialize("excludeWithLayerMask")
  13900. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13901. __decorate([
  13902. BABYLON.serialize("includeOnlyWithLayerMask")
  13903. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13904. __decorate([
  13905. BABYLON.serialize("lightmapMode")
  13906. ], Light.prototype, "_lightmapMode", void 0);
  13907. BABYLON.Light = Light;
  13908. })(BABYLON || (BABYLON = {}));
  13909. //# sourceMappingURL=babylon.light.js.map
  13910. var BABYLON;
  13911. (function (BABYLON) {
  13912. var Camera = (function (_super) {
  13913. __extends(Camera, _super);
  13914. function Camera(name, position, scene) {
  13915. var _this = _super.call(this, name, scene) || this;
  13916. _this.upVector = BABYLON.Vector3.Up();
  13917. _this.orthoLeft = null;
  13918. _this.orthoRight = null;
  13919. _this.orthoBottom = null;
  13920. _this.orthoTop = null;
  13921. _this.fov = 0.8;
  13922. _this.minZ = 1.0;
  13923. _this.maxZ = 10000.0;
  13924. _this.inertia = 0.9;
  13925. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13926. _this.isIntermediate = false;
  13927. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13928. _this.layerMask = 0x0FFFFFFF;
  13929. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13930. // Camera rig members
  13931. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13932. _this._rigCameras = new Array();
  13933. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13934. _this.customRenderTargets = new Array();
  13935. // Cache
  13936. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13937. _this._projectionMatrix = new BABYLON.Matrix();
  13938. _this._doNotComputeProjectionMatrix = false;
  13939. _this._postProcesses = new Array();
  13940. _this._transformMatrix = BABYLON.Matrix.Zero();
  13941. _this._activeMeshes = new BABYLON.SmartArray(256);
  13942. _this._globalPosition = BABYLON.Vector3.Zero();
  13943. _this._refreshFrustumPlanes = true;
  13944. _this.getScene().addCamera(_this);
  13945. if (!_this.getScene().activeCamera) {
  13946. _this.getScene().activeCamera = _this;
  13947. }
  13948. _this.position = position;
  13949. return _this;
  13950. }
  13951. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13952. get: function () {
  13953. return Camera._PERSPECTIVE_CAMERA;
  13954. },
  13955. enumerable: true,
  13956. configurable: true
  13957. });
  13958. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13959. get: function () {
  13960. return Camera._ORTHOGRAPHIC_CAMERA;
  13961. },
  13962. enumerable: true,
  13963. configurable: true
  13964. });
  13965. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13966. get: function () {
  13967. return Camera._FOVMODE_VERTICAL_FIXED;
  13968. },
  13969. enumerable: true,
  13970. configurable: true
  13971. });
  13972. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13973. get: function () {
  13974. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13975. },
  13976. enumerable: true,
  13977. configurable: true
  13978. });
  13979. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13980. get: function () {
  13981. return Camera._RIG_MODE_NONE;
  13982. },
  13983. enumerable: true,
  13984. configurable: true
  13985. });
  13986. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13987. get: function () {
  13988. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13989. },
  13990. enumerable: true,
  13991. configurable: true
  13992. });
  13993. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13994. get: function () {
  13995. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13996. },
  13997. enumerable: true,
  13998. configurable: true
  13999. });
  14000. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14001. get: function () {
  14002. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14003. },
  14004. enumerable: true,
  14005. configurable: true
  14006. });
  14007. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14008. get: function () {
  14009. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14010. },
  14011. enumerable: true,
  14012. configurable: true
  14013. });
  14014. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14015. get: function () {
  14016. return Camera._RIG_MODE_VR;
  14017. },
  14018. enumerable: true,
  14019. configurable: true
  14020. });
  14021. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14022. get: function () {
  14023. return Camera._RIG_MODE_WEBVR;
  14024. },
  14025. enumerable: true,
  14026. configurable: true
  14027. });
  14028. Camera.prototype.getClassName = function () {
  14029. return "Camera";
  14030. };
  14031. /**
  14032. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14033. */
  14034. Camera.prototype.toString = function (fullDetails) {
  14035. var ret = "Name: " + this.name;
  14036. ret += ", type: " + this.getClassName();
  14037. if (this.animations) {
  14038. for (var i = 0; i < this.animations.length; i++) {
  14039. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14040. }
  14041. }
  14042. if (fullDetails) {
  14043. }
  14044. return ret;
  14045. };
  14046. Object.defineProperty(Camera.prototype, "globalPosition", {
  14047. get: function () {
  14048. return this._globalPosition;
  14049. },
  14050. enumerable: true,
  14051. configurable: true
  14052. });
  14053. Camera.prototype.getActiveMeshes = function () {
  14054. return this._activeMeshes;
  14055. };
  14056. Camera.prototype.isActiveMesh = function (mesh) {
  14057. return (this._activeMeshes.indexOf(mesh) !== -1);
  14058. };
  14059. //Cache
  14060. Camera.prototype._initCache = function () {
  14061. _super.prototype._initCache.call(this);
  14062. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14063. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14064. this._cache.mode = undefined;
  14065. this._cache.minZ = undefined;
  14066. this._cache.maxZ = undefined;
  14067. this._cache.fov = undefined;
  14068. this._cache.fovMode = undefined;
  14069. this._cache.aspectRatio = undefined;
  14070. this._cache.orthoLeft = undefined;
  14071. this._cache.orthoRight = undefined;
  14072. this._cache.orthoBottom = undefined;
  14073. this._cache.orthoTop = undefined;
  14074. this._cache.renderWidth = undefined;
  14075. this._cache.renderHeight = undefined;
  14076. };
  14077. Camera.prototype._updateCache = function (ignoreParentClass) {
  14078. if (!ignoreParentClass) {
  14079. _super.prototype._updateCache.call(this);
  14080. }
  14081. var engine = this.getEngine();
  14082. this._cache.position.copyFrom(this.position);
  14083. this._cache.upVector.copyFrom(this.upVector);
  14084. this._cache.mode = this.mode;
  14085. this._cache.minZ = this.minZ;
  14086. this._cache.maxZ = this.maxZ;
  14087. this._cache.fov = this.fov;
  14088. this._cache.fovMode = this.fovMode;
  14089. this._cache.aspectRatio = engine.getAspectRatio(this);
  14090. this._cache.orthoLeft = this.orthoLeft;
  14091. this._cache.orthoRight = this.orthoRight;
  14092. this._cache.orthoBottom = this.orthoBottom;
  14093. this._cache.orthoTop = this.orthoTop;
  14094. this._cache.renderWidth = engine.getRenderWidth();
  14095. this._cache.renderHeight = engine.getRenderHeight();
  14096. };
  14097. Camera.prototype._updateFromScene = function () {
  14098. this.updateCache();
  14099. this.update();
  14100. };
  14101. // Synchronized
  14102. Camera.prototype._isSynchronized = function () {
  14103. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14104. };
  14105. Camera.prototype._isSynchronizedViewMatrix = function () {
  14106. if (!_super.prototype._isSynchronized.call(this))
  14107. return false;
  14108. return this._cache.position.equals(this.position)
  14109. && this._cache.upVector.equals(this.upVector)
  14110. && this.isSynchronizedWithParent();
  14111. };
  14112. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14113. var check = this._cache.mode === this.mode
  14114. && this._cache.minZ === this.minZ
  14115. && this._cache.maxZ === this.maxZ;
  14116. if (!check) {
  14117. return false;
  14118. }
  14119. var engine = this.getEngine();
  14120. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14121. check = this._cache.fov === this.fov
  14122. && this._cache.fovMode === this.fovMode
  14123. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14124. }
  14125. else {
  14126. check = this._cache.orthoLeft === this.orthoLeft
  14127. && this._cache.orthoRight === this.orthoRight
  14128. && this._cache.orthoBottom === this.orthoBottom
  14129. && this._cache.orthoTop === this.orthoTop
  14130. && this._cache.renderWidth === engine.getRenderWidth()
  14131. && this._cache.renderHeight === engine.getRenderHeight();
  14132. }
  14133. return check;
  14134. };
  14135. // Controls
  14136. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14137. };
  14138. Camera.prototype.detachControl = function (element) {
  14139. };
  14140. Camera.prototype.update = function () {
  14141. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14142. this._updateRigCameras();
  14143. }
  14144. this._checkInputs();
  14145. };
  14146. Camera.prototype._checkInputs = function () {
  14147. };
  14148. Object.defineProperty(Camera.prototype, "rigCameras", {
  14149. get: function () {
  14150. return this._rigCameras;
  14151. },
  14152. enumerable: true,
  14153. configurable: true
  14154. });
  14155. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14156. get: function () {
  14157. return this._rigPostProcess;
  14158. },
  14159. enumerable: true,
  14160. configurable: true
  14161. });
  14162. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14163. // invalidate framebuffer
  14164. if (this._postProcesses.length > 0) {
  14165. this._postProcesses[0].markTextureDirty();
  14166. }
  14167. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14168. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14169. var cam = this._rigCameras[i];
  14170. var rigPostProcess = cam._rigPostProcess;
  14171. // for VR rig, there does not have to be a post process
  14172. if (rigPostProcess) {
  14173. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14174. if (isPass) {
  14175. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14176. cam.isIntermediate = this._postProcesses.length === 0;
  14177. }
  14178. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14179. rigPostProcess.markTextureDirty();
  14180. }
  14181. else {
  14182. cam._postProcesses = this._postProcesses.slice(0);
  14183. }
  14184. }
  14185. };
  14186. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14187. if (insertAt === void 0) { insertAt = null; }
  14188. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14189. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14190. return 0;
  14191. }
  14192. if (insertAt == null || insertAt < 0) {
  14193. this._postProcesses.push(postProcess);
  14194. }
  14195. else {
  14196. this._postProcesses.splice(insertAt, 0, postProcess);
  14197. }
  14198. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14199. return this._postProcesses.indexOf(postProcess);
  14200. };
  14201. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14202. if (atIndices === void 0) { atIndices = null; }
  14203. var result = [];
  14204. var i;
  14205. var index;
  14206. if (!atIndices) {
  14207. var idx = this._postProcesses.indexOf(postProcess);
  14208. if (idx !== -1) {
  14209. this._postProcesses.splice(idx, 1);
  14210. }
  14211. }
  14212. else {
  14213. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14214. // iterate descending, so can just splice as we go
  14215. for (i = atIndices.length - 1; i >= 0; i--) {
  14216. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14217. result.push(i);
  14218. continue;
  14219. }
  14220. index = atIndices[i];
  14221. this._postProcesses.splice(index, 1);
  14222. }
  14223. }
  14224. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14225. return result;
  14226. };
  14227. Camera.prototype.getWorldMatrix = function () {
  14228. if (!this._worldMatrix) {
  14229. this._worldMatrix = BABYLON.Matrix.Identity();
  14230. }
  14231. var viewMatrix = this.getViewMatrix();
  14232. viewMatrix.invertToRef(this._worldMatrix);
  14233. return this._worldMatrix;
  14234. };
  14235. Camera.prototype._getViewMatrix = function () {
  14236. return BABYLON.Matrix.Identity();
  14237. };
  14238. Camera.prototype.getViewMatrix = function (force) {
  14239. this._computedViewMatrix = this._computeViewMatrix(force);
  14240. if (!force && this._isSynchronizedViewMatrix()) {
  14241. return this._computedViewMatrix;
  14242. }
  14243. this._refreshFrustumPlanes = true;
  14244. if (!this.parent || !this.parent.getWorldMatrix) {
  14245. this._globalPosition.copyFrom(this.position);
  14246. }
  14247. else {
  14248. if (!this._worldMatrix) {
  14249. this._worldMatrix = BABYLON.Matrix.Identity();
  14250. }
  14251. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14252. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14253. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14254. this._computedViewMatrix.invert();
  14255. this._markSyncedWithParent();
  14256. }
  14257. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14258. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14259. }
  14260. this._currentRenderId = this.getScene().getRenderId();
  14261. return this._computedViewMatrix;
  14262. };
  14263. Camera.prototype._computeViewMatrix = function (force) {
  14264. if (!force && this._isSynchronizedViewMatrix()) {
  14265. return this._computedViewMatrix;
  14266. }
  14267. this._computedViewMatrix = this._getViewMatrix();
  14268. this._currentRenderId = this.getScene().getRenderId();
  14269. return this._computedViewMatrix;
  14270. };
  14271. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14272. this._doNotComputeProjectionMatrix = true;
  14273. if (projection !== undefined) {
  14274. this._projectionMatrix = projection;
  14275. }
  14276. };
  14277. ;
  14278. Camera.prototype.unfreezeProjectionMatrix = function () {
  14279. this._doNotComputeProjectionMatrix = false;
  14280. };
  14281. ;
  14282. Camera.prototype.getProjectionMatrix = function (force) {
  14283. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14284. return this._projectionMatrix;
  14285. }
  14286. this._refreshFrustumPlanes = true;
  14287. var engine = this.getEngine();
  14288. var scene = this.getScene();
  14289. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14290. if (this.minZ <= 0) {
  14291. this.minZ = 0.1;
  14292. }
  14293. if (scene.useRightHandedSystem) {
  14294. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14295. }
  14296. else {
  14297. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14298. }
  14299. return this._projectionMatrix;
  14300. }
  14301. var halfWidth = engine.getRenderWidth() / 2.0;
  14302. var halfHeight = engine.getRenderHeight() / 2.0;
  14303. if (scene.useRightHandedSystem) {
  14304. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14305. }
  14306. else {
  14307. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14308. }
  14309. return this._projectionMatrix;
  14310. };
  14311. Camera.prototype.getTranformationMatrix = function () {
  14312. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14313. return this._transformMatrix;
  14314. };
  14315. Camera.prototype.updateFrustumPlanes = function () {
  14316. if (!this._refreshFrustumPlanes) {
  14317. return;
  14318. }
  14319. this.getTranformationMatrix();
  14320. if (!this._frustumPlanes) {
  14321. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14322. }
  14323. else {
  14324. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14325. }
  14326. this._refreshFrustumPlanes = false;
  14327. };
  14328. Camera.prototype.isInFrustum = function (target) {
  14329. this.updateFrustumPlanes();
  14330. return target.isInFrustum(this._frustumPlanes);
  14331. };
  14332. Camera.prototype.isCompletelyInFrustum = function (target) {
  14333. this.updateFrustumPlanes();
  14334. return target.isCompletelyInFrustum(this._frustumPlanes);
  14335. };
  14336. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14337. if (length === void 0) { length = 100; }
  14338. if (!transform) {
  14339. transform = this.getWorldMatrix();
  14340. }
  14341. if (!origin) {
  14342. origin = this.position;
  14343. }
  14344. var forward = new BABYLON.Vector3(0, 0, 1);
  14345. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14346. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14347. return new BABYLON.Ray(origin, direction, length);
  14348. };
  14349. Camera.prototype.dispose = function () {
  14350. // Animations
  14351. this.getScene().stopAnimation(this);
  14352. // Remove from scene
  14353. this.getScene().removeCamera(this);
  14354. while (this._rigCameras.length > 0) {
  14355. this._rigCameras.pop().dispose();
  14356. }
  14357. // Postprocesses
  14358. var i = this._postProcesses.length;
  14359. while (--i >= 0) {
  14360. this._postProcesses[i].dispose(this);
  14361. }
  14362. _super.prototype.dispose.call(this);
  14363. };
  14364. Object.defineProperty(Camera.prototype, "leftCamera", {
  14365. // ---- Camera rigs section ----
  14366. get: function () {
  14367. if (this._rigCameras.length < 1) {
  14368. return undefined;
  14369. }
  14370. return this._rigCameras[0];
  14371. },
  14372. enumerable: true,
  14373. configurable: true
  14374. });
  14375. Object.defineProperty(Camera.prototype, "rightCamera", {
  14376. get: function () {
  14377. if (this._rigCameras.length < 2) {
  14378. return undefined;
  14379. }
  14380. return this._rigCameras[1];
  14381. },
  14382. enumerable: true,
  14383. configurable: true
  14384. });
  14385. Camera.prototype.getLeftTarget = function () {
  14386. if (this._rigCameras.length < 1) {
  14387. return undefined;
  14388. }
  14389. return this._rigCameras[0].getTarget();
  14390. };
  14391. Camera.prototype.getRightTarget = function () {
  14392. if (this._rigCameras.length < 2) {
  14393. return undefined;
  14394. }
  14395. return this._rigCameras[1].getTarget();
  14396. };
  14397. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14398. while (this._rigCameras.length > 0) {
  14399. this._rigCameras.pop().dispose();
  14400. }
  14401. this.cameraRigMode = mode;
  14402. this._cameraRigParams = {};
  14403. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14404. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14405. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14406. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14407. // create the rig cameras, unless none
  14408. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14409. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14410. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14411. }
  14412. switch (this.cameraRigMode) {
  14413. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14414. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14415. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14416. break;
  14417. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14418. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14419. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14420. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14421. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14422. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14423. break;
  14424. case Camera.RIG_MODE_VR:
  14425. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14426. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14427. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14428. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14429. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14430. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14431. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14432. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14433. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14434. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14435. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14436. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14437. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14438. if (metrics.compensateDistortion) {
  14439. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14440. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14441. }
  14442. break;
  14443. case Camera.RIG_MODE_WEBVR:
  14444. if (rigParams.vrDisplay) {
  14445. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14446. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14447. //Left eye
  14448. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14449. this._rigCameras[0].setCameraRigParameter("left", true);
  14450. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14451. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14452. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14453. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14454. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14455. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14456. this._rigCameras[0].parent = this;
  14457. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14458. //Right eye
  14459. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14460. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14461. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14462. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14463. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14464. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14465. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14466. this._rigCameras[1].parent = this;
  14467. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14468. }
  14469. break;
  14470. }
  14471. this._cascadePostProcessesToRigCams();
  14472. this.
  14473. update();
  14474. };
  14475. Camera.prototype._getVRProjectionMatrix = function () {
  14476. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14477. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14478. return this._projectionMatrix;
  14479. };
  14480. Camera.prototype._updateCameraRotationMatrix = function () {
  14481. //Here for WebVR
  14482. };
  14483. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14484. //Here for WebVR
  14485. };
  14486. /**
  14487. * This function MUST be overwritten by the different WebVR cameras available.
  14488. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14489. */
  14490. Camera.prototype._getWebVRProjectionMatrix = function () {
  14491. return BABYLON.Matrix.Identity();
  14492. };
  14493. /**
  14494. * This function MUST be overwritten by the different WebVR cameras available.
  14495. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14496. */
  14497. Camera.prototype._getWebVRViewMatrix = function () {
  14498. return BABYLON.Matrix.Identity();
  14499. };
  14500. Camera.prototype.setCameraRigParameter = function (name, value) {
  14501. if (!this._cameraRigParams) {
  14502. this._cameraRigParams = {};
  14503. }
  14504. this._cameraRigParams[name] = value;
  14505. //provisionnally:
  14506. if (name === "interaxialDistance") {
  14507. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14508. }
  14509. };
  14510. /**
  14511. * needs to be overridden by children so sub has required properties to be copied
  14512. */
  14513. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14514. return null;
  14515. };
  14516. /**
  14517. * May need to be overridden by children
  14518. */
  14519. Camera.prototype._updateRigCameras = function () {
  14520. for (var i = 0; i < this._rigCameras.length; i++) {
  14521. this._rigCameras[i].minZ = this.minZ;
  14522. this._rigCameras[i].maxZ = this.maxZ;
  14523. this._rigCameras[i].fov = this.fov;
  14524. }
  14525. // only update viewport when ANAGLYPH
  14526. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14527. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14528. }
  14529. };
  14530. Camera.prototype._setupInputs = function () {
  14531. };
  14532. Camera.prototype.serialize = function () {
  14533. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14534. // Type
  14535. serializationObject.type = this.getClassName();
  14536. // Parent
  14537. if (this.parent) {
  14538. serializationObject.parentId = this.parent.id;
  14539. }
  14540. if (this.inputs) {
  14541. this.inputs.serialize(serializationObject);
  14542. }
  14543. // Animations
  14544. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14545. serializationObject.ranges = this.serializeAnimationRanges();
  14546. return serializationObject;
  14547. };
  14548. Camera.prototype.clone = function (name) {
  14549. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14550. };
  14551. Camera.prototype.getDirection = function (localAxis) {
  14552. var result = BABYLON.Vector3.Zero();
  14553. this.getDirectionToRef(localAxis, result);
  14554. return result;
  14555. };
  14556. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14557. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14558. };
  14559. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14560. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14561. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14562. switch (type) {
  14563. case "ArcRotateCamera":
  14564. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14565. case "DeviceOrientationCamera":
  14566. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14567. case "FollowCamera":
  14568. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14569. case "ArcFollowCamera":
  14570. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14571. case "GamepadCamera":
  14572. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14573. case "TouchCamera":
  14574. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14575. case "VirtualJoysticksCamera":
  14576. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14577. case "WebVRFreeCamera":
  14578. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14579. case "WebVRGamepadCamera":
  14580. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14581. case "VRDeviceOrientationFreeCamera":
  14582. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14583. case "VRDeviceOrientationGamepadCamera":
  14584. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14585. case "AnaglyphArcRotateCamera":
  14586. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14587. case "AnaglyphFreeCamera":
  14588. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14589. case "AnaglyphGamepadCamera":
  14590. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14591. case "AnaglyphUniversalCamera":
  14592. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14593. case "StereoscopicArcRotateCamera":
  14594. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14595. case "StereoscopicFreeCamera":
  14596. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14597. case "StereoscopicGamepadCamera":
  14598. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14599. case "StereoscopicUniversalCamera":
  14600. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14601. case "FreeCamera":
  14602. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14603. default:
  14604. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14605. }
  14606. };
  14607. Camera.Parse = function (parsedCamera, scene) {
  14608. var type = parsedCamera.type;
  14609. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14610. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14611. // Parent
  14612. if (parsedCamera.parentId) {
  14613. camera._waitingParentId = parsedCamera.parentId;
  14614. }
  14615. //If camera has an input manager, let it parse inputs settings
  14616. if (camera.inputs) {
  14617. camera.inputs.parse(parsedCamera);
  14618. camera._setupInputs();
  14619. }
  14620. if (camera.setPosition) {
  14621. camera.position.copyFromFloats(0, 0, 0);
  14622. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  14623. }
  14624. // Target
  14625. if (parsedCamera.target) {
  14626. if (camera.setTarget) {
  14627. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14628. }
  14629. }
  14630. // Apply 3d rig, when found
  14631. if (parsedCamera.cameraRigMode) {
  14632. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14633. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14634. }
  14635. // Animations
  14636. if (parsedCamera.animations) {
  14637. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14638. var parsedAnimation = parsedCamera.animations[animationIndex];
  14639. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14640. }
  14641. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14642. }
  14643. if (parsedCamera.autoAnimate) {
  14644. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14645. }
  14646. return camera;
  14647. };
  14648. return Camera;
  14649. }(BABYLON.Node));
  14650. // Statics
  14651. Camera._PERSPECTIVE_CAMERA = 0;
  14652. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14653. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14654. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14655. Camera._RIG_MODE_NONE = 0;
  14656. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14657. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14658. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14659. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14660. Camera._RIG_MODE_VR = 20;
  14661. Camera._RIG_MODE_WEBVR = 21;
  14662. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14663. __decorate([
  14664. BABYLON.serializeAsVector3()
  14665. ], Camera.prototype, "position", void 0);
  14666. __decorate([
  14667. BABYLON.serializeAsVector3()
  14668. ], Camera.prototype, "upVector", void 0);
  14669. __decorate([
  14670. BABYLON.serialize()
  14671. ], Camera.prototype, "orthoLeft", void 0);
  14672. __decorate([
  14673. BABYLON.serialize()
  14674. ], Camera.prototype, "orthoRight", void 0);
  14675. __decorate([
  14676. BABYLON.serialize()
  14677. ], Camera.prototype, "orthoBottom", void 0);
  14678. __decorate([
  14679. BABYLON.serialize()
  14680. ], Camera.prototype, "orthoTop", void 0);
  14681. __decorate([
  14682. BABYLON.serialize()
  14683. ], Camera.prototype, "fov", void 0);
  14684. __decorate([
  14685. BABYLON.serialize()
  14686. ], Camera.prototype, "minZ", void 0);
  14687. __decorate([
  14688. BABYLON.serialize()
  14689. ], Camera.prototype, "maxZ", void 0);
  14690. __decorate([
  14691. BABYLON.serialize()
  14692. ], Camera.prototype, "inertia", void 0);
  14693. __decorate([
  14694. BABYLON.serialize()
  14695. ], Camera.prototype, "mode", void 0);
  14696. __decorate([
  14697. BABYLON.serialize()
  14698. ], Camera.prototype, "layerMask", void 0);
  14699. __decorate([
  14700. BABYLON.serialize()
  14701. ], Camera.prototype, "fovMode", void 0);
  14702. __decorate([
  14703. BABYLON.serialize()
  14704. ], Camera.prototype, "cameraRigMode", void 0);
  14705. __decorate([
  14706. BABYLON.serialize()
  14707. ], Camera.prototype, "interaxialDistance", void 0);
  14708. __decorate([
  14709. BABYLON.serialize()
  14710. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14711. BABYLON.Camera = Camera;
  14712. })(BABYLON || (BABYLON = {}));
  14713. //# sourceMappingURL=babylon.camera.js.map
  14714. var BABYLON;
  14715. (function (BABYLON) {
  14716. var RenderingManager = (function () {
  14717. function RenderingManager(scene) {
  14718. this._renderingGroups = new Array();
  14719. this._autoClearDepthStencil = {};
  14720. this._customOpaqueSortCompareFn = {};
  14721. this._customAlphaTestSortCompareFn = {};
  14722. this._customTransparentSortCompareFn = {};
  14723. this._renderinGroupInfo = null;
  14724. this._scene = scene;
  14725. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14726. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14727. }
  14728. }
  14729. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14730. if (depth === void 0) { depth = true; }
  14731. if (stencil === void 0) { stencil = true; }
  14732. if (this._depthStencilBufferAlreadyCleaned) {
  14733. return;
  14734. }
  14735. this._scene.getEngine().clear(null, false, depth, stencil);
  14736. this._depthStencilBufferAlreadyCleaned = true;
  14737. };
  14738. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14739. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14740. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14741. var info = null;
  14742. if (observable) {
  14743. if (!this._renderinGroupInfo) {
  14744. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14745. }
  14746. info = this._renderinGroupInfo;
  14747. info.scene = this._scene;
  14748. info.camera = this._scene.activeCamera;
  14749. }
  14750. // Dispatch sprites
  14751. if (renderSprites) {
  14752. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14753. var manager = this._scene.spriteManagers[index];
  14754. this.dispatchSprites(manager);
  14755. }
  14756. }
  14757. // Render
  14758. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14759. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14760. var renderingGroup = this._renderingGroups[index];
  14761. if (!renderingGroup && !observable)
  14762. continue;
  14763. this._currentIndex = index;
  14764. var renderingGroupMask = 0;
  14765. // Fire PRECLEAR stage
  14766. if (observable) {
  14767. renderingGroupMask = Math.pow(2, index);
  14768. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14769. info.renderingGroupId = index;
  14770. observable.notifyObservers(info, renderingGroupMask);
  14771. }
  14772. // Clear depth/stencil if needed
  14773. if (RenderingManager.AUTOCLEAR) {
  14774. var autoClear = this._autoClearDepthStencil[index];
  14775. if (autoClear && autoClear.autoClear) {
  14776. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14777. }
  14778. }
  14779. if (observable) {
  14780. // Fire PREOPAQUE stage
  14781. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14782. observable.notifyObservers(info, renderingGroupMask);
  14783. // Fire PRETRANSPARENT stage
  14784. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14785. observable.notifyObservers(info, renderingGroupMask);
  14786. }
  14787. if (renderingGroup)
  14788. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14789. // Fire POSTTRANSPARENT stage
  14790. if (observable) {
  14791. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14792. observable.notifyObservers(info, renderingGroupMask);
  14793. }
  14794. }
  14795. };
  14796. RenderingManager.prototype.reset = function () {
  14797. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14798. var renderingGroup = this._renderingGroups[index];
  14799. if (renderingGroup) {
  14800. renderingGroup.prepare();
  14801. }
  14802. }
  14803. };
  14804. RenderingManager.prototype.dispose = function () {
  14805. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14806. var renderingGroup = this._renderingGroups[index];
  14807. if (renderingGroup) {
  14808. renderingGroup.dispose();
  14809. }
  14810. }
  14811. this._renderingGroups.length = 0;
  14812. };
  14813. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14814. if (!this._renderingGroups[renderingGroupId]) {
  14815. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14816. }
  14817. };
  14818. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14819. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14820. this._prepareRenderingGroup(renderingGroupId);
  14821. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14822. };
  14823. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14824. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14825. this._prepareRenderingGroup(renderingGroupId);
  14826. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14827. };
  14828. RenderingManager.prototype.dispatch = function (subMesh) {
  14829. var mesh = subMesh.getMesh();
  14830. var renderingGroupId = mesh.renderingGroupId || 0;
  14831. this._prepareRenderingGroup(renderingGroupId);
  14832. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14833. };
  14834. /**
  14835. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14836. * This allowed control for front to back rendering or reversly depending of the special needs.
  14837. *
  14838. * @param renderingGroupId The rendering group id corresponding to its index
  14839. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14840. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14841. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14842. */
  14843. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14844. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14845. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14846. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14847. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14848. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14849. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14850. if (this._renderingGroups[renderingGroupId]) {
  14851. var group = this._renderingGroups[renderingGroupId];
  14852. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14853. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14854. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14855. }
  14856. };
  14857. /**
  14858. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14859. *
  14860. * @param renderingGroupId The rendering group id corresponding to its index
  14861. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14862. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14863. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14864. */
  14865. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14866. if (depth === void 0) { depth = true; }
  14867. if (stencil === void 0) { stencil = true; }
  14868. this._autoClearDepthStencil[renderingGroupId] = {
  14869. autoClear: autoClearDepthStencil,
  14870. depth: depth,
  14871. stencil: stencil
  14872. };
  14873. };
  14874. return RenderingManager;
  14875. }());
  14876. /**
  14877. * The max id used for rendering groups (not included)
  14878. */
  14879. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14880. /**
  14881. * The min id used for rendering groups (included)
  14882. */
  14883. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14884. /**
  14885. * Used to globally prevent autoclearing scenes.
  14886. */
  14887. RenderingManager.AUTOCLEAR = true;
  14888. BABYLON.RenderingManager = RenderingManager;
  14889. })(BABYLON || (BABYLON = {}));
  14890. //# sourceMappingURL=babylon.renderingManager.js.map
  14891. var BABYLON;
  14892. (function (BABYLON) {
  14893. var RenderingGroup = (function () {
  14894. /**
  14895. * Creates a new rendering group.
  14896. * @param index The rendering group index
  14897. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14898. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14899. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14900. */
  14901. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14902. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14903. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14904. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14905. this.index = index;
  14906. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14907. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14908. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14909. this._particleSystems = new BABYLON.SmartArray(256);
  14910. this._spriteManagers = new BABYLON.SmartArray(256);
  14911. this._edgesRenderers = new BABYLON.SmartArray(16);
  14912. this._scene = scene;
  14913. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14914. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14915. this.transparentSortCompareFn = transparentSortCompareFn;
  14916. }
  14917. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14918. /**
  14919. * Set the opaque sort comparison function.
  14920. * If null the sub meshes will be render in the order they were created
  14921. */
  14922. set: function (value) {
  14923. this._opaqueSortCompareFn = value;
  14924. if (value) {
  14925. this._renderOpaque = this.renderOpaqueSorted;
  14926. }
  14927. else {
  14928. this._renderOpaque = RenderingGroup.renderUnsorted;
  14929. }
  14930. },
  14931. enumerable: true,
  14932. configurable: true
  14933. });
  14934. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14935. /**
  14936. * Set the alpha test sort comparison function.
  14937. * If null the sub meshes will be render in the order they were created
  14938. */
  14939. set: function (value) {
  14940. this._alphaTestSortCompareFn = value;
  14941. if (value) {
  14942. this._renderAlphaTest = this.renderAlphaTestSorted;
  14943. }
  14944. else {
  14945. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14946. }
  14947. },
  14948. enumerable: true,
  14949. configurable: true
  14950. });
  14951. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14952. /**
  14953. * Set the transparent sort comparison function.
  14954. * If null the sub meshes will be render in the order they were created
  14955. */
  14956. set: function (value) {
  14957. if (value) {
  14958. this._transparentSortCompareFn = value;
  14959. }
  14960. else {
  14961. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14962. }
  14963. this._renderTransparent = this.renderTransparentSorted;
  14964. },
  14965. enumerable: true,
  14966. configurable: true
  14967. });
  14968. /**
  14969. * Render all the sub meshes contained in the group.
  14970. * @param customRenderFunction Used to override the default render behaviour of the group.
  14971. * @returns true if rendered some submeshes.
  14972. */
  14973. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14974. if (customRenderFunction) {
  14975. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14976. return;
  14977. }
  14978. var engine = this._scene.getEngine();
  14979. // Opaque
  14980. if (this._opaqueSubMeshes.length !== 0) {
  14981. this._renderOpaque(this._opaqueSubMeshes);
  14982. }
  14983. // Alpha test
  14984. if (this._alphaTestSubMeshes.length !== 0) {
  14985. engine.setAlphaTesting(true);
  14986. this._renderAlphaTest(this._alphaTestSubMeshes);
  14987. engine.setAlphaTesting(false);
  14988. }
  14989. var stencilState = engine.getStencilBuffer();
  14990. engine.setStencilBuffer(false);
  14991. // Sprites
  14992. if (renderSprites) {
  14993. this._renderSprites();
  14994. }
  14995. // Particles
  14996. if (renderParticles) {
  14997. this._renderParticles(activeMeshes);
  14998. }
  14999. if (this.onBeforeTransparentRendering) {
  15000. this.onBeforeTransparentRendering();
  15001. }
  15002. // Transparent
  15003. if (this._transparentSubMeshes.length !== 0) {
  15004. this._renderTransparent(this._transparentSubMeshes);
  15005. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15006. }
  15007. engine.setStencilBuffer(stencilState);
  15008. // Edges
  15009. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15010. this._edgesRenderers.data[edgesRendererIndex].render();
  15011. }
  15012. };
  15013. /**
  15014. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15015. * @param subMeshes The submeshes to render
  15016. */
  15017. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15018. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15019. };
  15020. /**
  15021. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15022. * @param subMeshes The submeshes to render
  15023. */
  15024. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15025. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15026. };
  15027. /**
  15028. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15029. * @param subMeshes The submeshes to render
  15030. */
  15031. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15032. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15033. };
  15034. /**
  15035. * Renders the submeshes in a specified order.
  15036. * @param subMeshes The submeshes to sort before render
  15037. * @param sortCompareFn The comparison function use to sort
  15038. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15039. * @param transparent Specifies to activate blending if true
  15040. */
  15041. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15042. var subIndex = 0;
  15043. var subMesh;
  15044. for (; subIndex < subMeshes.length; subIndex++) {
  15045. subMesh = subMeshes.data[subIndex];
  15046. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15047. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15048. }
  15049. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15050. sortedArray.sort(sortCompareFn);
  15051. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15052. subMesh = sortedArray[subIndex];
  15053. subMesh.render(transparent);
  15054. }
  15055. };
  15056. /**
  15057. * Renders the submeshes in the order they were dispatched (no sort applied).
  15058. * @param subMeshes The submeshes to render
  15059. */
  15060. RenderingGroup.renderUnsorted = function (subMeshes) {
  15061. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15062. var submesh = subMeshes.data[subIndex];
  15063. submesh.render(false);
  15064. }
  15065. };
  15066. /**
  15067. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15068. * are rendered back to front if in the same alpha index.
  15069. *
  15070. * @param a The first submesh
  15071. * @param b The second submesh
  15072. * @returns The result of the comparison
  15073. */
  15074. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15075. // Alpha index first
  15076. if (a._alphaIndex > b._alphaIndex) {
  15077. return 1;
  15078. }
  15079. if (a._alphaIndex < b._alphaIndex) {
  15080. return -1;
  15081. }
  15082. // Then distance to camera
  15083. return RenderingGroup.backToFrontSortCompare(a, b);
  15084. };
  15085. /**
  15086. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15087. * are rendered back to front.
  15088. *
  15089. * @param a The first submesh
  15090. * @param b The second submesh
  15091. * @returns The result of the comparison
  15092. */
  15093. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15094. // Then distance to camera
  15095. if (a._distanceToCamera < b._distanceToCamera) {
  15096. return 1;
  15097. }
  15098. if (a._distanceToCamera > b._distanceToCamera) {
  15099. return -1;
  15100. }
  15101. return 0;
  15102. };
  15103. /**
  15104. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15105. * are rendered front to back (prevent overdraw).
  15106. *
  15107. * @param a The first submesh
  15108. * @param b The second submesh
  15109. * @returns The result of the comparison
  15110. */
  15111. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15112. // Then distance to camera
  15113. if (a._distanceToCamera < b._distanceToCamera) {
  15114. return -1;
  15115. }
  15116. if (a._distanceToCamera > b._distanceToCamera) {
  15117. return 1;
  15118. }
  15119. return 0;
  15120. };
  15121. /**
  15122. * Resets the different lists of submeshes to prepare a new frame.
  15123. */
  15124. RenderingGroup.prototype.prepare = function () {
  15125. this._opaqueSubMeshes.reset();
  15126. this._transparentSubMeshes.reset();
  15127. this._alphaTestSubMeshes.reset();
  15128. this._particleSystems.reset();
  15129. this._spriteManagers.reset();
  15130. this._edgesRenderers.reset();
  15131. };
  15132. RenderingGroup.prototype.dispose = function () {
  15133. this._opaqueSubMeshes.dispose();
  15134. this._transparentSubMeshes.dispose();
  15135. this._alphaTestSubMeshes.dispose();
  15136. this._particleSystems.dispose();
  15137. this._spriteManagers.dispose();
  15138. this._edgesRenderers.dispose();
  15139. };
  15140. /**
  15141. * Inserts the submesh in its correct queue depending on its material.
  15142. * @param subMesh The submesh to dispatch
  15143. */
  15144. RenderingGroup.prototype.dispatch = function (subMesh) {
  15145. var material = subMesh.getMaterial();
  15146. var mesh = subMesh.getMesh();
  15147. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15148. this._transparentSubMeshes.push(subMesh);
  15149. }
  15150. else if (material.needAlphaTesting()) {
  15151. this._alphaTestSubMeshes.push(subMesh);
  15152. }
  15153. else {
  15154. this._opaqueSubMeshes.push(subMesh); // Opaque
  15155. }
  15156. if (mesh._edgesRenderer) {
  15157. this._edgesRenderers.push(mesh._edgesRenderer);
  15158. }
  15159. };
  15160. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15161. this._spriteManagers.push(spriteManager);
  15162. };
  15163. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15164. this._particleSystems.push(particleSystem);
  15165. };
  15166. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15167. if (this._particleSystems.length === 0) {
  15168. return;
  15169. }
  15170. // Particles
  15171. var activeCamera = this._scene.activeCamera;
  15172. this._scene._particlesDuration.beginMonitoring();
  15173. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15174. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15175. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15176. continue;
  15177. }
  15178. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15179. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15180. }
  15181. }
  15182. this._scene._particlesDuration.endMonitoring(false);
  15183. };
  15184. RenderingGroup.prototype._renderSprites = function () {
  15185. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15186. return;
  15187. }
  15188. // Sprites
  15189. var activeCamera = this._scene.activeCamera;
  15190. this._scene._spritesDuration.beginMonitoring();
  15191. for (var id = 0; id < this._spriteManagers.length; id++) {
  15192. var spriteManager = this._spriteManagers.data[id];
  15193. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15194. spriteManager.render();
  15195. }
  15196. }
  15197. this._scene._spritesDuration.endMonitoring(false);
  15198. };
  15199. return RenderingGroup;
  15200. }());
  15201. BABYLON.RenderingGroup = RenderingGroup;
  15202. })(BABYLON || (BABYLON = {}));
  15203. //# sourceMappingURL=babylon.renderingGroup.js.map
  15204. var BABYLON;
  15205. (function (BABYLON) {
  15206. var ClickInfo = (function () {
  15207. function ClickInfo() {
  15208. this._singleClick = false;
  15209. this._doubleClick = false;
  15210. this._hasSwiped = false;
  15211. this._ignore = false;
  15212. }
  15213. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15214. get: function () {
  15215. return this._singleClick;
  15216. },
  15217. set: function (b) {
  15218. this._singleClick = b;
  15219. },
  15220. enumerable: true,
  15221. configurable: true
  15222. });
  15223. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15224. get: function () {
  15225. return this._doubleClick;
  15226. },
  15227. set: function (b) {
  15228. this._doubleClick = b;
  15229. },
  15230. enumerable: true,
  15231. configurable: true
  15232. });
  15233. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15234. get: function () {
  15235. return this._hasSwiped;
  15236. },
  15237. set: function (b) {
  15238. this._hasSwiped = b;
  15239. },
  15240. enumerable: true,
  15241. configurable: true
  15242. });
  15243. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15244. get: function () {
  15245. return this._ignore;
  15246. },
  15247. set: function (b) {
  15248. this._ignore = b;
  15249. },
  15250. enumerable: true,
  15251. configurable: true
  15252. });
  15253. return ClickInfo;
  15254. }());
  15255. var PointerEventTypes = (function () {
  15256. function PointerEventTypes() {
  15257. }
  15258. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15259. get: function () {
  15260. return PointerEventTypes._POINTERDOWN;
  15261. },
  15262. enumerable: true,
  15263. configurable: true
  15264. });
  15265. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15266. get: function () {
  15267. return PointerEventTypes._POINTERUP;
  15268. },
  15269. enumerable: true,
  15270. configurable: true
  15271. });
  15272. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15273. get: function () {
  15274. return PointerEventTypes._POINTERMOVE;
  15275. },
  15276. enumerable: true,
  15277. configurable: true
  15278. });
  15279. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15280. get: function () {
  15281. return PointerEventTypes._POINTERWHEEL;
  15282. },
  15283. enumerable: true,
  15284. configurable: true
  15285. });
  15286. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15287. get: function () {
  15288. return PointerEventTypes._POINTERPICK;
  15289. },
  15290. enumerable: true,
  15291. configurable: true
  15292. });
  15293. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15294. get: function () {
  15295. return PointerEventTypes._POINTERTAP;
  15296. },
  15297. enumerable: true,
  15298. configurable: true
  15299. });
  15300. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15301. get: function () {
  15302. return PointerEventTypes._POINTERDOUBLETAP;
  15303. },
  15304. enumerable: true,
  15305. configurable: true
  15306. });
  15307. return PointerEventTypes;
  15308. }());
  15309. PointerEventTypes._POINTERDOWN = 0x01;
  15310. PointerEventTypes._POINTERUP = 0x02;
  15311. PointerEventTypes._POINTERMOVE = 0x04;
  15312. PointerEventTypes._POINTERWHEEL = 0x08;
  15313. PointerEventTypes._POINTERPICK = 0x10;
  15314. PointerEventTypes._POINTERTAP = 0x20;
  15315. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15316. BABYLON.PointerEventTypes = PointerEventTypes;
  15317. var PointerInfoBase = (function () {
  15318. function PointerInfoBase(type, event) {
  15319. this.type = type;
  15320. this.event = event;
  15321. }
  15322. return PointerInfoBase;
  15323. }());
  15324. BABYLON.PointerInfoBase = PointerInfoBase;
  15325. /**
  15326. * This class is used to store pointer related info for the onPrePointerObservable event.
  15327. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15328. */
  15329. var PointerInfoPre = (function (_super) {
  15330. __extends(PointerInfoPre, _super);
  15331. function PointerInfoPre(type, event, localX, localY) {
  15332. var _this = _super.call(this, type, event) || this;
  15333. _this.skipOnPointerObservable = false;
  15334. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15335. return _this;
  15336. }
  15337. return PointerInfoPre;
  15338. }(PointerInfoBase));
  15339. BABYLON.PointerInfoPre = PointerInfoPre;
  15340. /**
  15341. * This type contains all the data related to a pointer event in Babylon.js.
  15342. * 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.
  15343. */
  15344. var PointerInfo = (function (_super) {
  15345. __extends(PointerInfo, _super);
  15346. function PointerInfo(type, event, pickInfo) {
  15347. var _this = _super.call(this, type, event) || this;
  15348. _this.pickInfo = pickInfo;
  15349. return _this;
  15350. }
  15351. return PointerInfo;
  15352. }(PointerInfoBase));
  15353. BABYLON.PointerInfo = PointerInfo;
  15354. /**
  15355. * This class is used by the onRenderingGroupObservable
  15356. */
  15357. var RenderingGroupInfo = (function () {
  15358. function RenderingGroupInfo() {
  15359. }
  15360. return RenderingGroupInfo;
  15361. }());
  15362. /**
  15363. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15364. * This stage will be fired no matter what
  15365. */
  15366. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15367. /**
  15368. * Called before opaque object are rendered.
  15369. * This stage will be fired only if there's 3D Opaque content to render
  15370. */
  15371. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15372. /**
  15373. * Called after the opaque objects are rendered and before the transparent ones
  15374. * This stage will be fired only if there's 3D transparent content to render
  15375. */
  15376. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15377. /**
  15378. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15379. * This stage will be fired no matter what
  15380. */
  15381. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15382. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15383. /**
  15384. * Represents a scene to be rendered by the engine.
  15385. * @see http://doc.babylonjs.com/page.php?p=21911
  15386. */
  15387. var Scene = (function () {
  15388. /**
  15389. * @constructor
  15390. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15391. */
  15392. function Scene(engine) {
  15393. // Members
  15394. this.autoClear = true;
  15395. this.autoClearDepthAndStencil = true;
  15396. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15397. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15398. this.forceWireframe = false;
  15399. this._forcePointsCloud = false;
  15400. this.forceShowBoundingBoxes = false;
  15401. this.animationsEnabled = true;
  15402. this.constantlyUpdateMeshUnderPointer = false;
  15403. this.hoverCursor = "pointer";
  15404. // Metadata
  15405. this.metadata = null;
  15406. // Events
  15407. /**
  15408. * An event triggered when the scene is disposed.
  15409. * @type {BABYLON.Observable}
  15410. */
  15411. this.onDisposeObservable = new BABYLON.Observable();
  15412. /**
  15413. * An event triggered before rendering the scene
  15414. * @type {BABYLON.Observable}
  15415. */
  15416. this.onBeforeRenderObservable = new BABYLON.Observable();
  15417. /**
  15418. * An event triggered after rendering the scene
  15419. * @type {BABYLON.Observable}
  15420. */
  15421. this.onAfterRenderObservable = new BABYLON.Observable();
  15422. /**
  15423. * An event triggered when the scene is ready
  15424. * @type {BABYLON.Observable}
  15425. */
  15426. this.onReadyObservable = new BABYLON.Observable();
  15427. /**
  15428. * An event triggered before rendering a camera
  15429. * @type {BABYLON.Observable}
  15430. */
  15431. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15432. /**
  15433. * An event triggered after rendering a camera
  15434. * @type {BABYLON.Observable}
  15435. */
  15436. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15437. /**
  15438. * An event triggered when a camera is created
  15439. * @type {BABYLON.Observable}
  15440. */
  15441. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15442. /**
  15443. * An event triggered when a camera is removed
  15444. * @type {BABYLON.Observable}
  15445. */
  15446. this.onCameraRemovedObservable = new BABYLON.Observable();
  15447. /**
  15448. * An event triggered when a light is created
  15449. * @type {BABYLON.Observable}
  15450. */
  15451. this.onNewLightAddedObservable = new BABYLON.Observable();
  15452. /**
  15453. * An event triggered when a light is removed
  15454. * @type {BABYLON.Observable}
  15455. */
  15456. this.onLightRemovedObservable = new BABYLON.Observable();
  15457. /**
  15458. * An event triggered when a geometry is created
  15459. * @type {BABYLON.Observable}
  15460. */
  15461. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15462. /**
  15463. * An event triggered when a geometry is removed
  15464. * @type {BABYLON.Observable}
  15465. */
  15466. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15467. /**
  15468. * An event triggered when a mesh is created
  15469. * @type {BABYLON.Observable}
  15470. */
  15471. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15472. /**
  15473. * An event triggered when a mesh is removed
  15474. * @type {BABYLON.Observable}
  15475. */
  15476. this.onMeshRemovedObservable = new BABYLON.Observable();
  15477. /**
  15478. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15479. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15480. * 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)
  15481. */
  15482. this.onRenderingGroupObservable = new BABYLON.Observable();
  15483. // Animations
  15484. this.animations = [];
  15485. /**
  15486. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  15487. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15488. */
  15489. this.onPrePointerObservable = new BABYLON.Observable();
  15490. /**
  15491. * Observable event triggered each time an input event is received from the rendering canvas
  15492. */
  15493. this.onPointerObservable = new BABYLON.Observable();
  15494. this._meshPickProceed = false;
  15495. this._previousHasSwiped = false;
  15496. this._currentPickResult = null;
  15497. this._previousPickResult = null;
  15498. this._isButtonPressed = false;
  15499. this._doubleClickOccured = false;
  15500. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  15501. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15502. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15503. this._startingPointerTime = 0;
  15504. this._previousStartingPointerTime = 0;
  15505. // Coordinate system
  15506. /**
  15507. * use right-handed coordinate system on this scene.
  15508. * @type {boolean}
  15509. */
  15510. this._useRightHandedSystem = false;
  15511. // Fog
  15512. /**
  15513. * is fog enabled on this scene.
  15514. * @type {boolean}
  15515. */
  15516. this._fogEnabled = true;
  15517. this._fogMode = Scene.FOGMODE_NONE;
  15518. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15519. this.fogDensity = 0.1;
  15520. this.fogStart = 0;
  15521. this.fogEnd = 1000.0;
  15522. // Lights
  15523. /**
  15524. * is shadow enabled on this scene.
  15525. * @type {boolean}
  15526. */
  15527. this._shadowsEnabled = true;
  15528. /**
  15529. * is light enabled on this scene.
  15530. * @type {boolean}
  15531. */
  15532. this._lightsEnabled = true;
  15533. /**
  15534. * All of the lights added to this scene.
  15535. * @see BABYLON.Light
  15536. * @type {BABYLON.Light[]}
  15537. */
  15538. this.lights = new Array();
  15539. // Cameras
  15540. /**
  15541. * All of the cameras added to this scene.
  15542. * @see BABYLON.Camera
  15543. * @type {BABYLON.Camera[]}
  15544. */
  15545. this.cameras = new Array();
  15546. this.activeCameras = new Array();
  15547. // Meshes
  15548. /**
  15549. * All of the (abstract) meshes added to this scene.
  15550. * @see BABYLON.AbstractMesh
  15551. * @type {BABYLON.AbstractMesh[]}
  15552. */
  15553. this.meshes = new Array();
  15554. // Geometries
  15555. this._geometries = new Array();
  15556. this.materials = new Array();
  15557. this.multiMaterials = new Array();
  15558. // Textures
  15559. this._texturesEnabled = true;
  15560. this.textures = new Array();
  15561. // Particles
  15562. this.particlesEnabled = true;
  15563. this.particleSystems = new Array();
  15564. // Sprites
  15565. this.spritesEnabled = true;
  15566. this.spriteManagers = new Array();
  15567. // Layers
  15568. this.layers = new Array();
  15569. this.highlightLayers = new Array();
  15570. // Skeletons
  15571. this._skeletonsEnabled = true;
  15572. this.skeletons = new Array();
  15573. // Morph targets
  15574. this.morphTargetManagers = new Array();
  15575. // Lens flares
  15576. this.lensFlaresEnabled = true;
  15577. this.lensFlareSystems = new Array();
  15578. // Collisions
  15579. this.collisionsEnabled = true;
  15580. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15581. // Postprocesses
  15582. this.postProcessesEnabled = true;
  15583. // Customs render targets
  15584. this.renderTargetsEnabled = true;
  15585. this.dumpNextRenderTargets = false;
  15586. this.customRenderTargets = new Array();
  15587. // Imported meshes
  15588. this.importedMeshesFiles = new Array();
  15589. // Probes
  15590. this.probesEnabled = true;
  15591. this.reflectionProbes = new Array();
  15592. this._actionManagers = new Array();
  15593. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15594. // Procedural textures
  15595. this.proceduralTexturesEnabled = true;
  15596. this._proceduralTextures = new Array();
  15597. this.soundTracks = new Array();
  15598. this._audioEnabled = true;
  15599. this._headphone = false;
  15600. // Performance counters
  15601. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15602. this._totalLightsCounter = new BABYLON.PerfCounter();
  15603. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15604. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15605. this._totalVertices = new BABYLON.PerfCounter();
  15606. this._activeIndices = new BABYLON.PerfCounter();
  15607. this._activeParticles = new BABYLON.PerfCounter();
  15608. this._lastFrameDuration = new BABYLON.PerfCounter();
  15609. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15610. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15611. this._particlesDuration = new BABYLON.PerfCounter();
  15612. this._renderDuration = new BABYLON.PerfCounter();
  15613. this._spritesDuration = new BABYLON.PerfCounter();
  15614. this._activeBones = new BABYLON.PerfCounter();
  15615. this._animationTime = 0;
  15616. this.animationTimeScale = 1;
  15617. this._renderId = 0;
  15618. this._executeWhenReadyTimeoutId = -1;
  15619. this._intermediateRendering = false;
  15620. this._viewUpdateFlag = -1;
  15621. this._projectionUpdateFlag = -1;
  15622. this._toBeDisposed = new BABYLON.SmartArray(256);
  15623. this._pendingData = []; //ANY
  15624. this._activeMeshes = new BABYLON.SmartArray(256);
  15625. this._processedMaterials = new BABYLON.SmartArray(256);
  15626. this._renderTargets = new BABYLON.SmartArray(256);
  15627. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15628. this._activeSkeletons = new BABYLON.SmartArray(32);
  15629. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15630. this._activeAnimatables = new Array();
  15631. this._transformMatrix = BABYLON.Matrix.Zero();
  15632. this.requireLightSorting = false;
  15633. this._uniqueIdCounter = 0;
  15634. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15635. this._engine.scenes.push(this);
  15636. this._uid = null;
  15637. this._renderingManager = new BABYLON.RenderingManager(this);
  15638. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15639. if (BABYLON.OutlineRenderer) {
  15640. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15641. }
  15642. this.attachControl();
  15643. if (BABYLON.SoundTrack) {
  15644. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15645. }
  15646. //simplification queue
  15647. if (BABYLON.SimplificationQueue) {
  15648. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15649. }
  15650. //collision coordinator initialization. For now legacy per default.
  15651. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15652. // Uniform Buffer
  15653. this._createUbo();
  15654. // Default Image processing definition.
  15655. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  15656. }
  15657. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15658. get: function () {
  15659. return Scene._FOGMODE_NONE;
  15660. },
  15661. enumerable: true,
  15662. configurable: true
  15663. });
  15664. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15665. get: function () {
  15666. return Scene._FOGMODE_EXP;
  15667. },
  15668. enumerable: true,
  15669. configurable: true
  15670. });
  15671. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15672. get: function () {
  15673. return Scene._FOGMODE_EXP2;
  15674. },
  15675. enumerable: true,
  15676. configurable: true
  15677. });
  15678. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15679. get: function () {
  15680. return Scene._FOGMODE_LINEAR;
  15681. },
  15682. enumerable: true,
  15683. configurable: true
  15684. });
  15685. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15686. /**
  15687. * Texture used in all pbr material as the reflection texture.
  15688. * As in the majority of the scene they are the same (exception for multi room and so on),
  15689. * this is easier to reference from here than from all the materials.
  15690. */
  15691. get: function () {
  15692. return this._environmentTexture;
  15693. },
  15694. /**
  15695. * Texture used in all pbr material as the reflection texture.
  15696. * As in the majority of the scene they are the same (exception for multi room and so on),
  15697. * this is easier to set here than in all the materials.
  15698. */
  15699. set: function (value) {
  15700. this._environmentTexture = value;
  15701. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15702. },
  15703. enumerable: true,
  15704. configurable: true
  15705. });
  15706. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  15707. /**
  15708. * Default image processing configuration used either in the rendering
  15709. * Forward main pass or through the imageProcessingPostProcess if present.
  15710. * As in the majority of the scene they are the same (exception for multi camera),
  15711. * this is easier to reference from here than from all the materials and post process.
  15712. *
  15713. * No setter as we it is a shared configuration, you can set the values instead.
  15714. */
  15715. get: function () {
  15716. return this._imageProcessingConfiguration;
  15717. },
  15718. enumerable: true,
  15719. configurable: true
  15720. });
  15721. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15722. get: function () {
  15723. return this._forcePointsCloud;
  15724. },
  15725. set: function (value) {
  15726. if (this._forcePointsCloud === value) {
  15727. return;
  15728. }
  15729. this._forcePointsCloud = value;
  15730. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15731. },
  15732. enumerable: true,
  15733. configurable: true
  15734. });
  15735. Object.defineProperty(Scene.prototype, "onDispose", {
  15736. set: function (callback) {
  15737. if (this._onDisposeObserver) {
  15738. this.onDisposeObservable.remove(this._onDisposeObserver);
  15739. }
  15740. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15741. },
  15742. enumerable: true,
  15743. configurable: true
  15744. });
  15745. Object.defineProperty(Scene.prototype, "beforeRender", {
  15746. set: function (callback) {
  15747. if (this._onBeforeRenderObserver) {
  15748. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15749. }
  15750. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15751. },
  15752. enumerable: true,
  15753. configurable: true
  15754. });
  15755. Object.defineProperty(Scene.prototype, "afterRender", {
  15756. set: function (callback) {
  15757. if (this._onAfterRenderObserver) {
  15758. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15759. }
  15760. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15761. },
  15762. enumerable: true,
  15763. configurable: true
  15764. });
  15765. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15766. set: function (callback) {
  15767. if (this._onBeforeCameraRenderObserver) {
  15768. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15769. }
  15770. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15771. },
  15772. enumerable: true,
  15773. configurable: true
  15774. });
  15775. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15776. set: function (callback) {
  15777. if (this._onAfterCameraRenderObserver) {
  15778. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15779. }
  15780. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15781. },
  15782. enumerable: true,
  15783. configurable: true
  15784. });
  15785. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15786. get: function () {
  15787. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15788. },
  15789. enumerable: true,
  15790. configurable: true
  15791. });
  15792. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15793. get: function () {
  15794. return this._useRightHandedSystem;
  15795. },
  15796. set: function (value) {
  15797. if (this._useRightHandedSystem === value) {
  15798. return;
  15799. }
  15800. this._useRightHandedSystem = value;
  15801. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15802. },
  15803. enumerable: true,
  15804. configurable: true
  15805. });
  15806. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15807. get: function () {
  15808. return this._fogEnabled;
  15809. },
  15810. set: function (value) {
  15811. if (this._fogEnabled === value) {
  15812. return;
  15813. }
  15814. this._fogEnabled = value;
  15815. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15816. },
  15817. enumerable: true,
  15818. configurable: true
  15819. });
  15820. Object.defineProperty(Scene.prototype, "fogMode", {
  15821. get: function () {
  15822. return this._fogMode;
  15823. },
  15824. set: function (value) {
  15825. if (this._fogMode === value) {
  15826. return;
  15827. }
  15828. this._fogMode = value;
  15829. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15830. },
  15831. enumerable: true,
  15832. configurable: true
  15833. });
  15834. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15835. get: function () {
  15836. return this._shadowsEnabled;
  15837. },
  15838. set: function (value) {
  15839. if (this._shadowsEnabled === value) {
  15840. return;
  15841. }
  15842. this._shadowsEnabled = value;
  15843. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15844. },
  15845. enumerable: true,
  15846. configurable: true
  15847. });
  15848. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15849. get: function () {
  15850. return this._lightsEnabled;
  15851. },
  15852. set: function (value) {
  15853. if (this._lightsEnabled === value) {
  15854. return;
  15855. }
  15856. this._lightsEnabled = value;
  15857. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15858. },
  15859. enumerable: true,
  15860. configurable: true
  15861. });
  15862. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15863. get: function () {
  15864. if (!this._defaultMaterial) {
  15865. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15866. }
  15867. return this._defaultMaterial;
  15868. },
  15869. set: function (value) {
  15870. this._defaultMaterial = value;
  15871. },
  15872. enumerable: true,
  15873. configurable: true
  15874. });
  15875. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15876. get: function () {
  15877. return this._texturesEnabled;
  15878. },
  15879. set: function (value) {
  15880. if (this._texturesEnabled === value) {
  15881. return;
  15882. }
  15883. this._texturesEnabled = value;
  15884. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15885. },
  15886. enumerable: true,
  15887. configurable: true
  15888. });
  15889. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15890. get: function () {
  15891. return this._skeletonsEnabled;
  15892. },
  15893. set: function (value) {
  15894. if (this._skeletonsEnabled === value) {
  15895. return;
  15896. }
  15897. this._skeletonsEnabled = value;
  15898. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15899. },
  15900. enumerable: true,
  15901. configurable: true
  15902. });
  15903. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15904. get: function () {
  15905. if (!this._postProcessRenderPipelineManager) {
  15906. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15907. }
  15908. return this._postProcessRenderPipelineManager;
  15909. },
  15910. enumerable: true,
  15911. configurable: true
  15912. });
  15913. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15914. get: function () {
  15915. return this._frustumPlanes;
  15916. },
  15917. enumerable: true,
  15918. configurable: true
  15919. });
  15920. Object.defineProperty(Scene.prototype, "debugLayer", {
  15921. // Properties
  15922. get: function () {
  15923. if (!this._debugLayer) {
  15924. this._debugLayer = new BABYLON.DebugLayer(this);
  15925. }
  15926. return this._debugLayer;
  15927. },
  15928. enumerable: true,
  15929. configurable: true
  15930. });
  15931. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15932. get: function () {
  15933. return this._workerCollisions;
  15934. },
  15935. set: function (enabled) {
  15936. if (!BABYLON.CollisionCoordinatorLegacy) {
  15937. return;
  15938. }
  15939. enabled = (enabled && !!Worker);
  15940. this._workerCollisions = enabled;
  15941. if (this.collisionCoordinator) {
  15942. this.collisionCoordinator.destroy();
  15943. }
  15944. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15945. this.collisionCoordinator.init(this);
  15946. },
  15947. enumerable: true,
  15948. configurable: true
  15949. });
  15950. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15951. get: function () {
  15952. return this._selectionOctree;
  15953. },
  15954. enumerable: true,
  15955. configurable: true
  15956. });
  15957. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15958. /**
  15959. * The mesh that is currently under the pointer.
  15960. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15961. */
  15962. get: function () {
  15963. return this._pointerOverMesh;
  15964. },
  15965. enumerable: true,
  15966. configurable: true
  15967. });
  15968. Object.defineProperty(Scene.prototype, "pointerX", {
  15969. /**
  15970. * Current on-screen X position of the pointer
  15971. * @return {number} X position of the pointer
  15972. */
  15973. get: function () {
  15974. return this._pointerX;
  15975. },
  15976. enumerable: true,
  15977. configurable: true
  15978. });
  15979. Object.defineProperty(Scene.prototype, "pointerY", {
  15980. /**
  15981. * Current on-screen Y position of the pointer
  15982. * @return {number} Y position of the pointer
  15983. */
  15984. get: function () {
  15985. return this._pointerY;
  15986. },
  15987. enumerable: true,
  15988. configurable: true
  15989. });
  15990. Scene.prototype.getCachedMaterial = function () {
  15991. return this._cachedMaterial;
  15992. };
  15993. Scene.prototype.getCachedEffect = function () {
  15994. return this._cachedEffect;
  15995. };
  15996. Scene.prototype.getCachedVisibility = function () {
  15997. return this._cachedVisibility;
  15998. };
  15999. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  16000. if (visibility === void 0) { visibility = 0; }
  16001. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16002. };
  16003. Scene.prototype.getBoundingBoxRenderer = function () {
  16004. if (!this._boundingBoxRenderer) {
  16005. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16006. }
  16007. return this._boundingBoxRenderer;
  16008. };
  16009. Scene.prototype.getOutlineRenderer = function () {
  16010. return this._outlineRenderer;
  16011. };
  16012. Scene.prototype.getEngine = function () {
  16013. return this._engine;
  16014. };
  16015. Scene.prototype.getTotalVertices = function () {
  16016. return this._totalVertices.current;
  16017. };
  16018. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16019. get: function () {
  16020. return this._totalVertices;
  16021. },
  16022. enumerable: true,
  16023. configurable: true
  16024. });
  16025. Scene.prototype.getActiveIndices = function () {
  16026. return this._activeIndices.current;
  16027. };
  16028. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16029. get: function () {
  16030. return this._activeIndices;
  16031. },
  16032. enumerable: true,
  16033. configurable: true
  16034. });
  16035. Scene.prototype.getActiveParticles = function () {
  16036. return this._activeParticles.current;
  16037. };
  16038. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16039. get: function () {
  16040. return this._activeParticles;
  16041. },
  16042. enumerable: true,
  16043. configurable: true
  16044. });
  16045. Scene.prototype.getActiveBones = function () {
  16046. return this._activeBones.current;
  16047. };
  16048. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16049. get: function () {
  16050. return this._activeBones;
  16051. },
  16052. enumerable: true,
  16053. configurable: true
  16054. });
  16055. // Stats
  16056. Scene.prototype.getLastFrameDuration = function () {
  16057. return this._lastFrameDuration.current;
  16058. };
  16059. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16060. get: function () {
  16061. return this._lastFrameDuration;
  16062. },
  16063. enumerable: true,
  16064. configurable: true
  16065. });
  16066. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16067. return this._evaluateActiveMeshesDuration.current;
  16068. };
  16069. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16070. get: function () {
  16071. return this._evaluateActiveMeshesDuration;
  16072. },
  16073. enumerable: true,
  16074. configurable: true
  16075. });
  16076. Scene.prototype.getActiveMeshes = function () {
  16077. return this._activeMeshes;
  16078. };
  16079. Scene.prototype.getRenderTargetsDuration = function () {
  16080. return this._renderTargetsDuration.current;
  16081. };
  16082. Scene.prototype.getRenderDuration = function () {
  16083. return this._renderDuration.current;
  16084. };
  16085. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16086. get: function () {
  16087. return this._renderDuration;
  16088. },
  16089. enumerable: true,
  16090. configurable: true
  16091. });
  16092. Scene.prototype.getParticlesDuration = function () {
  16093. return this._particlesDuration.current;
  16094. };
  16095. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16096. get: function () {
  16097. return this._particlesDuration;
  16098. },
  16099. enumerable: true,
  16100. configurable: true
  16101. });
  16102. Scene.prototype.getSpritesDuration = function () {
  16103. return this._spritesDuration.current;
  16104. };
  16105. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16106. get: function () {
  16107. return this._spritesDuration;
  16108. },
  16109. enumerable: true,
  16110. configurable: true
  16111. });
  16112. Scene.prototype.getAnimationRatio = function () {
  16113. return this._animationRatio;
  16114. };
  16115. Scene.prototype.getRenderId = function () {
  16116. return this._renderId;
  16117. };
  16118. Scene.prototype.incrementRenderId = function () {
  16119. this._renderId++;
  16120. };
  16121. Scene.prototype._updatePointerPosition = function (evt) {
  16122. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16123. this._pointerX = evt.clientX - canvasRect.left;
  16124. this._pointerY = evt.clientY - canvasRect.top;
  16125. this._unTranslatedPointerX = this._pointerX;
  16126. this._unTranslatedPointerY = this._pointerY;
  16127. if (this.cameraToUseForPointers) {
  16128. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16129. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16130. }
  16131. };
  16132. Scene.prototype._createUbo = function () {
  16133. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16134. this._sceneUbo.addUniform("viewProjection", 16);
  16135. this._sceneUbo.addUniform("view", 16);
  16136. };
  16137. // Pointers handling
  16138. /**
  16139. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16140. * @param attachUp defines if you want to attach events to pointerup
  16141. * @param attachDown defines if you want to attach events to pointerdown
  16142. * @param attachMove defines if you want to attach events to pointermove
  16143. */
  16144. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16145. var _this = this;
  16146. if (attachUp === void 0) { attachUp = true; }
  16147. if (attachDown === void 0) { attachDown = true; }
  16148. if (attachMove === void 0) { attachMove = true; }
  16149. this._initActionManager = function (act, clickInfo) {
  16150. if (!_this._meshPickProceed) {
  16151. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16152. _this._currentPickResult = pickResult;
  16153. if (pickResult) {
  16154. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16155. }
  16156. _this._meshPickProceed = true;
  16157. }
  16158. return act;
  16159. };
  16160. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16161. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16162. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16163. btn !== _this._previousButtonPressed) {
  16164. _this._doubleClickOccured = false;
  16165. clickInfo.singleClick = true;
  16166. clickInfo.ignore = false;
  16167. cb(clickInfo, _this._currentPickResult);
  16168. }
  16169. };
  16170. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16171. var clickInfo = new ClickInfo();
  16172. _this._currentPickResult = null;
  16173. var act;
  16174. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16175. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16176. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16177. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16178. act = _this._initActionManager(act, clickInfo);
  16179. if (act)
  16180. checkPicking = act.hasPickTriggers;
  16181. }
  16182. if (checkPicking) {
  16183. var btn = evt.button;
  16184. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16185. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16186. if (!clickInfo.hasSwiped) {
  16187. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16188. if (!checkSingleClickImmediately) {
  16189. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16190. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16191. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16192. act = _this._initActionManager(act, clickInfo);
  16193. if (act)
  16194. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16195. }
  16196. }
  16197. if (checkSingleClickImmediately) {
  16198. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16199. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16200. btn !== _this._previousButtonPressed) {
  16201. clickInfo.singleClick = true;
  16202. cb(clickInfo, _this._currentPickResult);
  16203. }
  16204. }
  16205. else {
  16206. // wait that no double click has been raised during the double click delay
  16207. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16208. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16209. }
  16210. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16211. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16212. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16213. act = _this._initActionManager(act, clickInfo);
  16214. if (act)
  16215. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16216. }
  16217. if (checkDoubleClick) {
  16218. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16219. if (btn === _this._previousButtonPressed &&
  16220. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16221. !_this._doubleClickOccured) {
  16222. // pointer has not moved for 2 clicks, it's a double click
  16223. if (!clickInfo.hasSwiped &&
  16224. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16225. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16226. _this._previousStartingPointerTime = 0;
  16227. _this._doubleClickOccured = true;
  16228. clickInfo.doubleClick = true;
  16229. clickInfo.ignore = false;
  16230. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16231. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16232. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16233. cb(clickInfo, _this._currentPickResult);
  16234. }
  16235. else {
  16236. _this._doubleClickOccured = false;
  16237. _this._previousStartingPointerTime = _this._startingPointerTime;
  16238. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16239. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16240. _this._previousButtonPressed = btn;
  16241. _this._previousHasSwiped = clickInfo.hasSwiped;
  16242. if (Scene.ExclusiveDoubleClickMode) {
  16243. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16244. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16245. }
  16246. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16247. cb(clickInfo, _this._previousPickResult);
  16248. }
  16249. else {
  16250. cb(clickInfo, _this._currentPickResult);
  16251. }
  16252. }
  16253. }
  16254. else {
  16255. _this._doubleClickOccured = false;
  16256. _this._previousStartingPointerTime = _this._startingPointerTime;
  16257. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16258. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16259. _this._previousButtonPressed = btn;
  16260. _this._previousHasSwiped = clickInfo.hasSwiped;
  16261. }
  16262. }
  16263. }
  16264. }
  16265. clickInfo.ignore = true;
  16266. cb(clickInfo, _this._currentPickResult);
  16267. };
  16268. var spritePredicate = function (sprite) {
  16269. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16270. };
  16271. this._onPointerMove = function (evt) {
  16272. _this._updatePointerPosition(evt);
  16273. // PreObservable support
  16274. if (_this.onPrePointerObservable.hasObservers()) {
  16275. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16276. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16277. _this.onPrePointerObservable.notifyObservers(pi, type);
  16278. if (pi.skipOnPointerObservable) {
  16279. return;
  16280. }
  16281. }
  16282. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16283. return;
  16284. }
  16285. var canvas = _this._engine.getRenderingCanvas();
  16286. if (!_this.pointerMovePredicate) {
  16287. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16288. }
  16289. // Meshes
  16290. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16291. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16292. _this.setPointerOverSprite(null);
  16293. _this.setPointerOverMesh(pickResult.pickedMesh);
  16294. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16295. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16296. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16297. }
  16298. else {
  16299. canvas.style.cursor = _this.hoverCursor;
  16300. }
  16301. }
  16302. else {
  16303. canvas.style.cursor = "";
  16304. }
  16305. }
  16306. else {
  16307. _this.setPointerOverMesh(null);
  16308. // Sprites
  16309. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16310. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16311. _this.setPointerOverSprite(pickResult.pickedSprite);
  16312. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16313. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16314. }
  16315. else {
  16316. canvas.style.cursor = _this.hoverCursor;
  16317. }
  16318. }
  16319. else {
  16320. _this.setPointerOverSprite(null);
  16321. // Restore pointer
  16322. canvas.style.cursor = "";
  16323. }
  16324. }
  16325. if (_this.onPointerMove) {
  16326. _this.onPointerMove(evt, pickResult);
  16327. }
  16328. if (_this.onPointerObservable.hasObservers()) {
  16329. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16330. var pi = new PointerInfo(type, evt, pickResult);
  16331. _this.onPointerObservable.notifyObservers(pi, type);
  16332. }
  16333. };
  16334. this._onPointerDown = function (evt) {
  16335. _this._isButtonPressed = true;
  16336. _this._pickedDownMesh = null;
  16337. _this._meshPickProceed = false;
  16338. _this._updatePointerPosition(evt);
  16339. // PreObservable support
  16340. if (_this.onPrePointerObservable.hasObservers()) {
  16341. var type = PointerEventTypes.POINTERDOWN;
  16342. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16343. _this.onPrePointerObservable.notifyObservers(pi, type);
  16344. if (pi.skipOnPointerObservable) {
  16345. return;
  16346. }
  16347. }
  16348. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16349. return;
  16350. }
  16351. _this._startingPointerPosition.x = _this._pointerX;
  16352. _this._startingPointerPosition.y = _this._pointerY;
  16353. _this._startingPointerTime = new Date().getTime();
  16354. if (!_this.pointerDownPredicate) {
  16355. _this.pointerDownPredicate = function (mesh) {
  16356. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16357. };
  16358. }
  16359. // Meshes
  16360. _this._pickedDownMesh = null;
  16361. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16362. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16363. _this._pickedDownMesh = pickResult.pickedMesh;
  16364. var actionManager = pickResult.pickedMesh.actionManager;
  16365. if (actionManager) {
  16366. if (actionManager.hasPickTriggers) {
  16367. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16368. switch (evt.button) {
  16369. case 0:
  16370. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16371. break;
  16372. case 1:
  16373. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16374. break;
  16375. case 2:
  16376. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16377. break;
  16378. }
  16379. }
  16380. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16381. window.setTimeout((function () {
  16382. var _this = this;
  16383. 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);
  16384. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16385. if (this._isButtonPressed &&
  16386. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16387. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16388. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16389. this._startingPointerTime = 0;
  16390. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16391. }
  16392. }
  16393. }).bind(_this), Scene.LongPressDelay);
  16394. }
  16395. }
  16396. }
  16397. if (_this.onPointerDown) {
  16398. _this.onPointerDown(evt, pickResult);
  16399. }
  16400. if (_this.onPointerObservable.hasObservers()) {
  16401. var type = PointerEventTypes.POINTERDOWN;
  16402. var pi = new PointerInfo(type, evt, pickResult);
  16403. _this.onPointerObservable.notifyObservers(pi, type);
  16404. }
  16405. // Sprites
  16406. _this._pickedDownSprite = null;
  16407. if (_this.spriteManagers.length > 0) {
  16408. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16409. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16410. if (pickResult.pickedSprite.actionManager) {
  16411. _this._pickedDownSprite = pickResult.pickedSprite;
  16412. switch (evt.button) {
  16413. case 0:
  16414. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16415. break;
  16416. case 1:
  16417. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16418. break;
  16419. case 2:
  16420. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16421. break;
  16422. }
  16423. if (pickResult.pickedSprite.actionManager) {
  16424. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16425. }
  16426. }
  16427. }
  16428. }
  16429. };
  16430. this._onPointerUp = function (evt) {
  16431. _this._isButtonPressed = false;
  16432. _this._pickedUpMesh = null;
  16433. _this._meshPickProceed = false;
  16434. _this._updatePointerPosition(evt);
  16435. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16436. // PreObservable support
  16437. if (this.onPrePointerObservable.hasObservers()) {
  16438. if (!clickInfo.ignore) {
  16439. if (!clickInfo.hasSwiped) {
  16440. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16441. var type = PointerEventTypes.POINTERTAP;
  16442. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16443. this.onPrePointerObservable.notifyObservers(pi, type);
  16444. if (pi.skipOnPointerObservable) {
  16445. return;
  16446. }
  16447. }
  16448. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16449. var type = PointerEventTypes.POINTERDOUBLETAP;
  16450. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16451. this.onPrePointerObservable.notifyObservers(pi, type);
  16452. if (pi.skipOnPointerObservable) {
  16453. return;
  16454. }
  16455. }
  16456. }
  16457. }
  16458. else {
  16459. var type = PointerEventTypes.POINTERUP;
  16460. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16461. this.onPrePointerObservable.notifyObservers(pi, type);
  16462. if (pi.skipOnPointerObservable) {
  16463. return;
  16464. }
  16465. }
  16466. }
  16467. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16468. return;
  16469. }
  16470. if (!this.pointerUpPredicate) {
  16471. this.pointerUpPredicate = function (mesh) {
  16472. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16473. };
  16474. }
  16475. // Meshes
  16476. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16477. this._initActionManager(null, clickInfo);
  16478. }
  16479. if (!pickResult) {
  16480. pickResult = this._currentPickResult;
  16481. }
  16482. if (pickResult && pickResult && pickResult.pickedMesh) {
  16483. this._pickedUpMesh = pickResult.pickedMesh;
  16484. if (this._pickedDownMesh === this._pickedUpMesh) {
  16485. if (this.onPointerPick) {
  16486. this.onPointerPick(evt, pickResult);
  16487. }
  16488. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16489. var type = PointerEventTypes.POINTERPICK;
  16490. var pi = new PointerInfo(type, evt, pickResult);
  16491. this.onPointerObservable.notifyObservers(pi, type);
  16492. }
  16493. }
  16494. if (pickResult.pickedMesh.actionManager) {
  16495. if (clickInfo.ignore) {
  16496. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16497. }
  16498. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16499. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16500. }
  16501. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16502. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16503. }
  16504. }
  16505. }
  16506. if (this._pickedDownMesh &&
  16507. this._pickedDownMesh.actionManager &&
  16508. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16509. this._pickedDownMesh !== this._pickedUpMesh) {
  16510. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16511. }
  16512. if (this.onPointerUp) {
  16513. this.onPointerUp(evt, pickResult);
  16514. }
  16515. if (this.onPointerObservable.hasObservers()) {
  16516. if (!clickInfo.ignore) {
  16517. if (!clickInfo.hasSwiped) {
  16518. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16519. var type = PointerEventTypes.POINTERTAP;
  16520. var pi = new PointerInfo(type, evt, pickResult);
  16521. this.onPointerObservable.notifyObservers(pi, type);
  16522. }
  16523. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16524. var type = PointerEventTypes.POINTERDOUBLETAP;
  16525. var pi = new PointerInfo(type, evt, pickResult);
  16526. this.onPointerObservable.notifyObservers(pi, type);
  16527. }
  16528. }
  16529. }
  16530. else {
  16531. var type = PointerEventTypes.POINTERUP;
  16532. var pi = new PointerInfo(type, evt, pickResult);
  16533. this.onPointerObservable.notifyObservers(pi, type);
  16534. }
  16535. }
  16536. // Sprites
  16537. if (this.spriteManagers.length > 0) {
  16538. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16539. if (pickResult.hit && pickResult.pickedSprite) {
  16540. if (pickResult.pickedSprite.actionManager) {
  16541. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16542. if (pickResult.pickedSprite.actionManager) {
  16543. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16544. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16545. }
  16546. }
  16547. }
  16548. }
  16549. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16550. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16551. }
  16552. }
  16553. this._previousPickResult = this._currentPickResult;
  16554. }).bind(_this));
  16555. };
  16556. this._onKeyDown = function (evt) {
  16557. if (_this.actionManager) {
  16558. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16559. }
  16560. };
  16561. this._onKeyUp = function (evt) {
  16562. if (_this.actionManager) {
  16563. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16564. }
  16565. };
  16566. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16567. var canvas = this._engine.getRenderingCanvas();
  16568. if (attachMove) {
  16569. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16570. // Wheel
  16571. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16572. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16573. }
  16574. if (attachDown) {
  16575. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16576. }
  16577. if (attachUp) {
  16578. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16579. }
  16580. canvas.tabIndex = 1;
  16581. canvas.addEventListener("keydown", this._onKeyDown, false);
  16582. canvas.addEventListener("keyup", this._onKeyUp, false);
  16583. };
  16584. Scene.prototype.detachControl = function () {
  16585. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16586. var canvas = this._engine.getRenderingCanvas();
  16587. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16588. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16589. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16590. // Wheel
  16591. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16592. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16593. canvas.removeEventListener("keydown", this._onKeyDown);
  16594. canvas.removeEventListener("keyup", this._onKeyUp);
  16595. };
  16596. // Ready
  16597. Scene.prototype.isReady = function () {
  16598. if (this._pendingData.length > 0) {
  16599. return false;
  16600. }
  16601. var index;
  16602. // Geometries
  16603. for (index = 0; index < this._geometries.length; index++) {
  16604. var geometry = this._geometries[index];
  16605. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16606. return false;
  16607. }
  16608. }
  16609. // Meshes
  16610. for (index = 0; index < this.meshes.length; index++) {
  16611. var mesh = this.meshes[index];
  16612. if (!mesh.isEnabled()) {
  16613. continue;
  16614. }
  16615. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16616. continue;
  16617. }
  16618. if (!mesh.isReady()) {
  16619. return false;
  16620. }
  16621. var mat = mesh.material;
  16622. if (mat) {
  16623. if (!mat.isReady(mesh)) {
  16624. return false;
  16625. }
  16626. }
  16627. }
  16628. return true;
  16629. };
  16630. Scene.prototype.resetCachedMaterial = function () {
  16631. this._cachedMaterial = null;
  16632. this._cachedEffect = null;
  16633. this._cachedVisibility = null;
  16634. };
  16635. Scene.prototype.registerBeforeRender = function (func) {
  16636. this.onBeforeRenderObservable.add(func);
  16637. };
  16638. Scene.prototype.unregisterBeforeRender = function (func) {
  16639. this.onBeforeRenderObservable.removeCallback(func);
  16640. };
  16641. Scene.prototype.registerAfterRender = function (func) {
  16642. this.onAfterRenderObservable.add(func);
  16643. };
  16644. Scene.prototype.unregisterAfterRender = function (func) {
  16645. this.onAfterRenderObservable.removeCallback(func);
  16646. };
  16647. Scene.prototype._addPendingData = function (data) {
  16648. this._pendingData.push(data);
  16649. };
  16650. Scene.prototype._removePendingData = function (data) {
  16651. var index = this._pendingData.indexOf(data);
  16652. if (index !== -1) {
  16653. this._pendingData.splice(index, 1);
  16654. }
  16655. };
  16656. Scene.prototype.getWaitingItemsCount = function () {
  16657. return this._pendingData.length;
  16658. };
  16659. /**
  16660. * Registers a function to be executed when the scene is ready.
  16661. * @param {Function} func - the function to be executed.
  16662. */
  16663. Scene.prototype.executeWhenReady = function (func) {
  16664. var _this = this;
  16665. this.onReadyObservable.add(func);
  16666. if (this._executeWhenReadyTimeoutId !== -1) {
  16667. return;
  16668. }
  16669. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16670. _this._checkIsReady();
  16671. }, 150);
  16672. };
  16673. Scene.prototype._checkIsReady = function () {
  16674. var _this = this;
  16675. if (this.isReady()) {
  16676. this.onReadyObservable.notifyObservers(this);
  16677. this.onReadyObservable.clear();
  16678. this._executeWhenReadyTimeoutId = -1;
  16679. return;
  16680. }
  16681. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16682. _this._checkIsReady();
  16683. }, 150);
  16684. };
  16685. // Animations
  16686. /**
  16687. * Will start the animation sequence of a given target
  16688. * @param target - the target
  16689. * @param {number} from - from which frame should animation start
  16690. * @param {number} to - till which frame should animation run.
  16691. * @param {boolean} [loop] - should the animation loop
  16692. * @param {number} [speedRatio] - the speed in which to run the animation
  16693. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16694. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16695. * @return {BABYLON.Animatable} the animatable object created for this animation
  16696. * @see BABYLON.Animatable
  16697. * @see http://doc.babylonjs.com/page.php?p=22081
  16698. */
  16699. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16700. if (speedRatio === void 0) { speedRatio = 1.0; }
  16701. if (from > to && speedRatio > 0) {
  16702. speedRatio *= -1;
  16703. }
  16704. this.stopAnimation(target);
  16705. if (!animatable) {
  16706. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16707. }
  16708. // Local animations
  16709. if (target.animations) {
  16710. animatable.appendAnimations(target, target.animations);
  16711. }
  16712. // Children animations
  16713. if (target.getAnimatables) {
  16714. var animatables = target.getAnimatables();
  16715. for (var index = 0; index < animatables.length; index++) {
  16716. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16717. }
  16718. }
  16719. animatable.reset();
  16720. return animatable;
  16721. };
  16722. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16723. if (speedRatio === undefined) {
  16724. speedRatio = 1.0;
  16725. }
  16726. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16727. return animatable;
  16728. };
  16729. Scene.prototype.getAnimatableByTarget = function (target) {
  16730. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16731. if (this._activeAnimatables[index].target === target) {
  16732. return this._activeAnimatables[index];
  16733. }
  16734. }
  16735. return null;
  16736. };
  16737. Object.defineProperty(Scene.prototype, "Animatables", {
  16738. get: function () {
  16739. return this._activeAnimatables;
  16740. },
  16741. enumerable: true,
  16742. configurable: true
  16743. });
  16744. /**
  16745. * Will stop the animation of the given target
  16746. * @param target - the target
  16747. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16748. * @see beginAnimation
  16749. */
  16750. Scene.prototype.stopAnimation = function (target, animationName) {
  16751. var animatable = this.getAnimatableByTarget(target);
  16752. if (animatable) {
  16753. animatable.stop(animationName);
  16754. }
  16755. };
  16756. Scene.prototype._animate = function () {
  16757. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16758. return;
  16759. }
  16760. // Getting time
  16761. var now = BABYLON.Tools.Now;
  16762. if (!this._animationTimeLast) {
  16763. if (this._pendingData.length > 0) {
  16764. return;
  16765. }
  16766. this._animationTimeLast = now;
  16767. }
  16768. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16769. this._animationTime += deltaTime;
  16770. this._animationTimeLast = now;
  16771. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16772. this._activeAnimatables[index]._animate(this._animationTime);
  16773. }
  16774. };
  16775. // Matrix
  16776. Scene.prototype.getViewMatrix = function () {
  16777. return this._viewMatrix;
  16778. };
  16779. Scene.prototype.getProjectionMatrix = function () {
  16780. return this._projectionMatrix;
  16781. };
  16782. Scene.prototype.getTransformMatrix = function () {
  16783. return this._transformMatrix;
  16784. };
  16785. Scene.prototype.setTransformMatrix = function (view, projection) {
  16786. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16787. return;
  16788. }
  16789. this._viewUpdateFlag = view.updateFlag;
  16790. this._projectionUpdateFlag = projection.updateFlag;
  16791. this._viewMatrix = view;
  16792. this._projectionMatrix = projection;
  16793. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16794. // Update frustum
  16795. if (!this._frustumPlanes) {
  16796. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16797. }
  16798. else {
  16799. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16800. }
  16801. if (this._sceneUbo.useUbo) {
  16802. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16803. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16804. this._sceneUbo.update();
  16805. }
  16806. };
  16807. Scene.prototype.getSceneUniformBuffer = function () {
  16808. return this._sceneUbo;
  16809. };
  16810. // Methods
  16811. Scene.prototype.getUniqueId = function () {
  16812. var result = this._uniqueIdCounter;
  16813. this._uniqueIdCounter++;
  16814. return result;
  16815. };
  16816. Scene.prototype.addMesh = function (newMesh) {
  16817. newMesh.uniqueId = this.getUniqueId();
  16818. var position = this.meshes.push(newMesh);
  16819. //notify the collision coordinator
  16820. if (this.collisionCoordinator) {
  16821. this.collisionCoordinator.onMeshAdded(newMesh);
  16822. }
  16823. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16824. };
  16825. Scene.prototype.removeMesh = function (toRemove) {
  16826. var index = this.meshes.indexOf(toRemove);
  16827. if (index !== -1) {
  16828. // Remove from the scene if mesh found
  16829. this.meshes.splice(index, 1);
  16830. }
  16831. //notify the collision coordinator
  16832. if (this.collisionCoordinator) {
  16833. this.collisionCoordinator.onMeshRemoved(toRemove);
  16834. }
  16835. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16836. return index;
  16837. };
  16838. Scene.prototype.removeSkeleton = function (toRemove) {
  16839. var index = this.skeletons.indexOf(toRemove);
  16840. if (index !== -1) {
  16841. // Remove from the scene if found
  16842. this.skeletons.splice(index, 1);
  16843. }
  16844. return index;
  16845. };
  16846. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16847. var index = this.morphTargetManagers.indexOf(toRemove);
  16848. if (index !== -1) {
  16849. // Remove from the scene if found
  16850. this.morphTargetManagers.splice(index, 1);
  16851. }
  16852. return index;
  16853. };
  16854. Scene.prototype.removeLight = function (toRemove) {
  16855. var index = this.lights.indexOf(toRemove);
  16856. if (index !== -1) {
  16857. // Remove from the scene if mesh found
  16858. this.lights.splice(index, 1);
  16859. this.sortLightsByPriority();
  16860. }
  16861. this.onLightRemovedObservable.notifyObservers(toRemove);
  16862. return index;
  16863. };
  16864. Scene.prototype.removeCamera = function (toRemove) {
  16865. var index = this.cameras.indexOf(toRemove);
  16866. if (index !== -1) {
  16867. // Remove from the scene if mesh found
  16868. this.cameras.splice(index, 1);
  16869. }
  16870. // Remove from activeCameras
  16871. var index2 = this.activeCameras.indexOf(toRemove);
  16872. if (index2 !== -1) {
  16873. // Remove from the scene if mesh found
  16874. this.activeCameras.splice(index2, 1);
  16875. }
  16876. // Reset the activeCamera
  16877. if (this.activeCamera === toRemove) {
  16878. if (this.cameras.length > 0) {
  16879. this.activeCamera = this.cameras[0];
  16880. }
  16881. else {
  16882. this.activeCamera = null;
  16883. }
  16884. }
  16885. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16886. return index;
  16887. };
  16888. Scene.prototype.addLight = function (newLight) {
  16889. newLight.uniqueId = this.getUniqueId();
  16890. this.lights.push(newLight);
  16891. this.sortLightsByPriority();
  16892. this.onNewLightAddedObservable.notifyObservers(newLight);
  16893. };
  16894. Scene.prototype.sortLightsByPriority = function () {
  16895. if (this.requireLightSorting) {
  16896. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16897. }
  16898. };
  16899. Scene.prototype.addCamera = function (newCamera) {
  16900. newCamera.uniqueId = this.getUniqueId();
  16901. var position = this.cameras.push(newCamera);
  16902. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16903. };
  16904. /**
  16905. * Switch active camera
  16906. * @param {Camera} newCamera - new active camera
  16907. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16908. */
  16909. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16910. if (attachControl === void 0) { attachControl = true; }
  16911. var canvas = this._engine.getRenderingCanvas();
  16912. this.activeCamera.detachControl(canvas);
  16913. this.activeCamera = newCamera;
  16914. if (attachControl) {
  16915. newCamera.attachControl(canvas);
  16916. }
  16917. };
  16918. /**
  16919. * sets the active camera of the scene using its ID
  16920. * @param {string} id - the camera's ID
  16921. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16922. * @see activeCamera
  16923. */
  16924. Scene.prototype.setActiveCameraByID = function (id) {
  16925. var camera = this.getCameraByID(id);
  16926. if (camera) {
  16927. this.activeCamera = camera;
  16928. return camera;
  16929. }
  16930. return null;
  16931. };
  16932. /**
  16933. * sets the active camera of the scene using its name
  16934. * @param {string} name - the camera's name
  16935. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16936. * @see activeCamera
  16937. */
  16938. Scene.prototype.setActiveCameraByName = function (name) {
  16939. var camera = this.getCameraByName(name);
  16940. if (camera) {
  16941. this.activeCamera = camera;
  16942. return camera;
  16943. }
  16944. return null;
  16945. };
  16946. /**
  16947. * get a material using its id
  16948. * @param {string} the material's ID
  16949. * @return {BABYLON.Material|null} the material or null if none found.
  16950. */
  16951. Scene.prototype.getMaterialByID = function (id) {
  16952. for (var index = 0; index < this.materials.length; index++) {
  16953. if (this.materials[index].id === id) {
  16954. return this.materials[index];
  16955. }
  16956. }
  16957. return null;
  16958. };
  16959. /**
  16960. * get a material using its name
  16961. * @param {string} the material's name
  16962. * @return {BABYLON.Material|null} the material or null if none found.
  16963. */
  16964. Scene.prototype.getMaterialByName = function (name) {
  16965. for (var index = 0; index < this.materials.length; index++) {
  16966. if (this.materials[index].name === name) {
  16967. return this.materials[index];
  16968. }
  16969. }
  16970. return null;
  16971. };
  16972. Scene.prototype.getLensFlareSystemByName = function (name) {
  16973. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16974. if (this.lensFlareSystems[index].name === name) {
  16975. return this.lensFlareSystems[index];
  16976. }
  16977. }
  16978. return null;
  16979. };
  16980. Scene.prototype.getLensFlareSystemByID = function (id) {
  16981. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16982. if (this.lensFlareSystems[index].id === id) {
  16983. return this.lensFlareSystems[index];
  16984. }
  16985. }
  16986. return null;
  16987. };
  16988. Scene.prototype.getCameraByID = function (id) {
  16989. for (var index = 0; index < this.cameras.length; index++) {
  16990. if (this.cameras[index].id === id) {
  16991. return this.cameras[index];
  16992. }
  16993. }
  16994. return null;
  16995. };
  16996. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16997. for (var index = 0; index < this.cameras.length; index++) {
  16998. if (this.cameras[index].uniqueId === uniqueId) {
  16999. return this.cameras[index];
  17000. }
  17001. }
  17002. return null;
  17003. };
  17004. /**
  17005. * get a camera using its name
  17006. * @param {string} the camera's name
  17007. * @return {BABYLON.Camera|null} the camera or null if none found.
  17008. */
  17009. Scene.prototype.getCameraByName = function (name) {
  17010. for (var index = 0; index < this.cameras.length; index++) {
  17011. if (this.cameras[index].name === name) {
  17012. return this.cameras[index];
  17013. }
  17014. }
  17015. return null;
  17016. };
  17017. /**
  17018. * get a bone using its id
  17019. * @param {string} the bone's id
  17020. * @return {BABYLON.Bone|null} the bone or null if not found
  17021. */
  17022. Scene.prototype.getBoneByID = function (id) {
  17023. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17024. var skeleton = this.skeletons[skeletonIndex];
  17025. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17026. if (skeleton.bones[boneIndex].id === id) {
  17027. return skeleton.bones[boneIndex];
  17028. }
  17029. }
  17030. }
  17031. return null;
  17032. };
  17033. /**
  17034. * get a bone using its id
  17035. * @param {string} the bone's name
  17036. * @return {BABYLON.Bone|null} the bone or null if not found
  17037. */
  17038. Scene.prototype.getBoneByName = function (name) {
  17039. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17040. var skeleton = this.skeletons[skeletonIndex];
  17041. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17042. if (skeleton.bones[boneIndex].name === name) {
  17043. return skeleton.bones[boneIndex];
  17044. }
  17045. }
  17046. }
  17047. return null;
  17048. };
  17049. /**
  17050. * get a light node using its name
  17051. * @param {string} the light's name
  17052. * @return {BABYLON.Light|null} the light or null if none found.
  17053. */
  17054. Scene.prototype.getLightByName = function (name) {
  17055. for (var index = 0; index < this.lights.length; index++) {
  17056. if (this.lights[index].name === name) {
  17057. return this.lights[index];
  17058. }
  17059. }
  17060. return null;
  17061. };
  17062. /**
  17063. * get a light node using its ID
  17064. * @param {string} the light's id
  17065. * @return {BABYLON.Light|null} the light or null if none found.
  17066. */
  17067. Scene.prototype.getLightByID = function (id) {
  17068. for (var index = 0; index < this.lights.length; index++) {
  17069. if (this.lights[index].id === id) {
  17070. return this.lights[index];
  17071. }
  17072. }
  17073. return null;
  17074. };
  17075. /**
  17076. * get a light node using its scene-generated unique ID
  17077. * @param {number} the light's unique id
  17078. * @return {BABYLON.Light|null} the light or null if none found.
  17079. */
  17080. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17081. for (var index = 0; index < this.lights.length; index++) {
  17082. if (this.lights[index].uniqueId === uniqueId) {
  17083. return this.lights[index];
  17084. }
  17085. }
  17086. return null;
  17087. };
  17088. /**
  17089. * get a particle system by id
  17090. * @param id {number} the particle system id
  17091. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17092. */
  17093. Scene.prototype.getParticleSystemByID = function (id) {
  17094. for (var index = 0; index < this.particleSystems.length; index++) {
  17095. if (this.particleSystems[index].id === id) {
  17096. return this.particleSystems[index];
  17097. }
  17098. }
  17099. return null;
  17100. };
  17101. /**
  17102. * get a geometry using its ID
  17103. * @param {string} the geometry's id
  17104. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17105. */
  17106. Scene.prototype.getGeometryByID = function (id) {
  17107. for (var index = 0; index < this._geometries.length; index++) {
  17108. if (this._geometries[index].id === id) {
  17109. return this._geometries[index];
  17110. }
  17111. }
  17112. return null;
  17113. };
  17114. /**
  17115. * add a new geometry to this scene.
  17116. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17117. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17118. * @return {boolean} was the geometry added or not
  17119. */
  17120. Scene.prototype.pushGeometry = function (geometry, force) {
  17121. if (!force && this.getGeometryByID(geometry.id)) {
  17122. return false;
  17123. }
  17124. this._geometries.push(geometry);
  17125. //notify the collision coordinator
  17126. if (this.collisionCoordinator) {
  17127. this.collisionCoordinator.onGeometryAdded(geometry);
  17128. }
  17129. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17130. return true;
  17131. };
  17132. /**
  17133. * Removes an existing geometry
  17134. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17135. * @return {boolean} was the geometry removed or not
  17136. */
  17137. Scene.prototype.removeGeometry = function (geometry) {
  17138. var index = this._geometries.indexOf(geometry);
  17139. if (index > -1) {
  17140. this._geometries.splice(index, 1);
  17141. //notify the collision coordinator
  17142. if (this.collisionCoordinator) {
  17143. this.collisionCoordinator.onGeometryDeleted(geometry);
  17144. }
  17145. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17146. return true;
  17147. }
  17148. return false;
  17149. };
  17150. Scene.prototype.getGeometries = function () {
  17151. return this._geometries;
  17152. };
  17153. /**
  17154. * Get the first added mesh found of a given ID
  17155. * @param {string} id - the id to search for
  17156. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17157. */
  17158. Scene.prototype.getMeshByID = function (id) {
  17159. for (var index = 0; index < this.meshes.length; index++) {
  17160. if (this.meshes[index].id === id) {
  17161. return this.meshes[index];
  17162. }
  17163. }
  17164. return null;
  17165. };
  17166. Scene.prototype.getMeshesByID = function (id) {
  17167. return this.meshes.filter(function (m) {
  17168. return m.id === id;
  17169. });
  17170. };
  17171. /**
  17172. * Get a mesh with its auto-generated unique id
  17173. * @param {number} uniqueId - the unique id to search for
  17174. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17175. */
  17176. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17177. for (var index = 0; index < this.meshes.length; index++) {
  17178. if (this.meshes[index].uniqueId === uniqueId) {
  17179. return this.meshes[index];
  17180. }
  17181. }
  17182. return null;
  17183. };
  17184. /**
  17185. * Get a the last added mesh found of a given ID
  17186. * @param {string} id - the id to search for
  17187. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17188. */
  17189. Scene.prototype.getLastMeshByID = function (id) {
  17190. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17191. if (this.meshes[index].id === id) {
  17192. return this.meshes[index];
  17193. }
  17194. }
  17195. return null;
  17196. };
  17197. /**
  17198. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17199. * @param {string} id - the id to search for
  17200. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17201. */
  17202. Scene.prototype.getLastEntryByID = function (id) {
  17203. var index;
  17204. for (index = this.meshes.length - 1; index >= 0; index--) {
  17205. if (this.meshes[index].id === id) {
  17206. return this.meshes[index];
  17207. }
  17208. }
  17209. for (index = this.cameras.length - 1; index >= 0; index--) {
  17210. if (this.cameras[index].id === id) {
  17211. return this.cameras[index];
  17212. }
  17213. }
  17214. for (index = this.lights.length - 1; index >= 0; index--) {
  17215. if (this.lights[index].id === id) {
  17216. return this.lights[index];
  17217. }
  17218. }
  17219. return null;
  17220. };
  17221. Scene.prototype.getNodeByID = function (id) {
  17222. var mesh = this.getMeshByID(id);
  17223. if (mesh) {
  17224. return mesh;
  17225. }
  17226. var light = this.getLightByID(id);
  17227. if (light) {
  17228. return light;
  17229. }
  17230. var camera = this.getCameraByID(id);
  17231. if (camera) {
  17232. return camera;
  17233. }
  17234. var bone = this.getBoneByID(id);
  17235. return bone;
  17236. };
  17237. Scene.prototype.getNodeByName = function (name) {
  17238. var mesh = this.getMeshByName(name);
  17239. if (mesh) {
  17240. return mesh;
  17241. }
  17242. var light = this.getLightByName(name);
  17243. if (light) {
  17244. return light;
  17245. }
  17246. var camera = this.getCameraByName(name);
  17247. if (camera) {
  17248. return camera;
  17249. }
  17250. var bone = this.getBoneByName(name);
  17251. return bone;
  17252. };
  17253. Scene.prototype.getMeshByName = function (name) {
  17254. for (var index = 0; index < this.meshes.length; index++) {
  17255. if (this.meshes[index].name === name) {
  17256. return this.meshes[index];
  17257. }
  17258. }
  17259. return null;
  17260. };
  17261. Scene.prototype.getSoundByName = function (name) {
  17262. var index;
  17263. if (BABYLON.AudioEngine) {
  17264. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17265. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17266. return this.mainSoundTrack.soundCollection[index];
  17267. }
  17268. }
  17269. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17270. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17271. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17272. return this.soundTracks[sdIndex].soundCollection[index];
  17273. }
  17274. }
  17275. }
  17276. }
  17277. return null;
  17278. };
  17279. Scene.prototype.getLastSkeletonByID = function (id) {
  17280. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17281. if (this.skeletons[index].id === id) {
  17282. return this.skeletons[index];
  17283. }
  17284. }
  17285. return null;
  17286. };
  17287. Scene.prototype.getSkeletonById = function (id) {
  17288. for (var index = 0; index < this.skeletons.length; index++) {
  17289. if (this.skeletons[index].id === id) {
  17290. return this.skeletons[index];
  17291. }
  17292. }
  17293. return null;
  17294. };
  17295. Scene.prototype.getSkeletonByName = function (name) {
  17296. for (var index = 0; index < this.skeletons.length; index++) {
  17297. if (this.skeletons[index].name === name) {
  17298. return this.skeletons[index];
  17299. }
  17300. }
  17301. return null;
  17302. };
  17303. Scene.prototype.getMorphTargetManagerById = function (id) {
  17304. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17305. if (this.morphTargetManagers[index].uniqueId === id) {
  17306. return this.morphTargetManagers[index];
  17307. }
  17308. }
  17309. return null;
  17310. };
  17311. Scene.prototype.isActiveMesh = function (mesh) {
  17312. return (this._activeMeshes.indexOf(mesh) !== -1);
  17313. };
  17314. /**
  17315. * Return a the first highlight layer of the scene with a given name.
  17316. * @param name The name of the highlight layer to look for.
  17317. * @return The highlight layer if found otherwise null.
  17318. */
  17319. Scene.prototype.getHighlightLayerByName = function (name) {
  17320. for (var index = 0; index < this.highlightLayers.length; index++) {
  17321. if (this.highlightLayers[index].name === name) {
  17322. return this.highlightLayers[index];
  17323. }
  17324. }
  17325. return null;
  17326. };
  17327. Object.defineProperty(Scene.prototype, "uid", {
  17328. /**
  17329. * Return a unique id as a string which can serve as an identifier for the scene
  17330. */
  17331. get: function () {
  17332. if (!this._uid) {
  17333. this._uid = BABYLON.Tools.RandomId();
  17334. }
  17335. return this._uid;
  17336. },
  17337. enumerable: true,
  17338. configurable: true
  17339. });
  17340. /**
  17341. * Add an externaly attached data from its key.
  17342. * This method call will fail and return false, if such key already exists.
  17343. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17344. * @param key the unique key that identifies the data
  17345. * @param data the data object to associate to the key for this Engine instance
  17346. * @return true if no such key were already present and the data was added successfully, false otherwise
  17347. */
  17348. Scene.prototype.addExternalData = function (key, data) {
  17349. if (!this._externalData) {
  17350. this._externalData = new BABYLON.StringDictionary();
  17351. }
  17352. return this._externalData.add(key, data);
  17353. };
  17354. /**
  17355. * Get an externaly attached data from its key
  17356. * @param key the unique key that identifies the data
  17357. * @return the associated data, if present (can be null), or undefined if not present
  17358. */
  17359. Scene.prototype.getExternalData = function (key) {
  17360. if (!this._externalData) {
  17361. return null;
  17362. }
  17363. return this._externalData.get(key);
  17364. };
  17365. /**
  17366. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17367. * @param key the unique key that identifies the data
  17368. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17369. * @return the associated data, can be null if the factory returned null.
  17370. */
  17371. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17372. if (!this._externalData) {
  17373. this._externalData = new BABYLON.StringDictionary();
  17374. }
  17375. return this._externalData.getOrAddWithFactory(key, factory);
  17376. };
  17377. /**
  17378. * Remove an externaly attached data from the Engine instance
  17379. * @param key the unique key that identifies the data
  17380. * @return true if the data was successfully removed, false if it doesn't exist
  17381. */
  17382. Scene.prototype.removeExternalData = function (key) {
  17383. return this._externalData.remove(key);
  17384. };
  17385. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17386. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17387. var material = subMesh.getMaterial();
  17388. if (mesh.showSubMeshesBoundingBox) {
  17389. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17390. }
  17391. if (material) {
  17392. // Render targets
  17393. if (material.getRenderTargetTextures) {
  17394. if (this._processedMaterials.indexOf(material) === -1) {
  17395. this._processedMaterials.push(material);
  17396. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17397. }
  17398. }
  17399. // Dispatch
  17400. this._activeIndices.addCount(subMesh.indexCount, false);
  17401. this._renderingManager.dispatch(subMesh);
  17402. }
  17403. }
  17404. };
  17405. Scene.prototype._isInIntermediateRendering = function () {
  17406. return this._intermediateRendering;
  17407. };
  17408. Scene.prototype._evaluateActiveMeshes = function () {
  17409. this.activeCamera._activeMeshes.reset();
  17410. this._activeMeshes.reset();
  17411. this._renderingManager.reset();
  17412. this._processedMaterials.reset();
  17413. this._activeParticleSystems.reset();
  17414. this._activeSkeletons.reset();
  17415. this._softwareSkinnedMeshes.reset();
  17416. if (this._boundingBoxRenderer) {
  17417. this._boundingBoxRenderer.reset();
  17418. }
  17419. // Meshes
  17420. var meshes;
  17421. var len;
  17422. if (this._selectionOctree) {
  17423. var selection = this._selectionOctree.select(this._frustumPlanes);
  17424. meshes = selection.data;
  17425. len = selection.length;
  17426. }
  17427. else {
  17428. len = this.meshes.length;
  17429. meshes = this.meshes;
  17430. }
  17431. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17432. var mesh = meshes[meshIndex];
  17433. if (mesh.isBlocked) {
  17434. continue;
  17435. }
  17436. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17437. if (!mesh.isReady() || !mesh.isEnabled()) {
  17438. continue;
  17439. }
  17440. mesh.computeWorldMatrix();
  17441. // Intersections
  17442. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17443. this._meshesForIntersections.pushNoDuplicate(mesh);
  17444. }
  17445. // Switch to current LOD
  17446. var meshLOD = mesh.getLOD(this.activeCamera);
  17447. if (!meshLOD) {
  17448. continue;
  17449. }
  17450. mesh._preActivate();
  17451. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17452. this._activeMeshes.push(mesh);
  17453. this.activeCamera._activeMeshes.push(mesh);
  17454. mesh._activate(this._renderId);
  17455. this._activeMesh(mesh, meshLOD);
  17456. }
  17457. }
  17458. // Particle systems
  17459. this._particlesDuration.beginMonitoring();
  17460. var beforeParticlesDate = BABYLON.Tools.Now;
  17461. if (this.particlesEnabled) {
  17462. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17463. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17464. var particleSystem = this.particleSystems[particleIndex];
  17465. if (!particleSystem.isStarted()) {
  17466. continue;
  17467. }
  17468. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17469. this._activeParticleSystems.push(particleSystem);
  17470. particleSystem.animate();
  17471. this._renderingManager.dispatchParticles(particleSystem);
  17472. }
  17473. }
  17474. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17475. }
  17476. this._particlesDuration.endMonitoring(false);
  17477. };
  17478. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17479. if (mesh.skeleton && this.skeletonsEnabled) {
  17480. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17481. mesh.skeleton.prepare();
  17482. }
  17483. if (!mesh.computeBonesUsingShaders) {
  17484. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17485. }
  17486. }
  17487. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17488. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17489. }
  17490. if (mesh && mesh.subMeshes) {
  17491. // Submeshes Octrees
  17492. var len;
  17493. var subMeshes;
  17494. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17495. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17496. len = intersections.length;
  17497. subMeshes = intersections.data;
  17498. }
  17499. else {
  17500. subMeshes = mesh.subMeshes;
  17501. len = subMeshes.length;
  17502. }
  17503. for (var subIndex = 0; subIndex < len; subIndex++) {
  17504. var subMesh = subMeshes[subIndex];
  17505. this._evaluateSubMesh(subMesh, mesh);
  17506. }
  17507. }
  17508. };
  17509. Scene.prototype.updateTransformMatrix = function (force) {
  17510. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17511. };
  17512. Scene.prototype._renderForCamera = function (camera) {
  17513. var engine = this._engine;
  17514. var startTime = BABYLON.Tools.Now;
  17515. this.activeCamera = camera;
  17516. if (!this.activeCamera)
  17517. throw new Error("Active camera not set");
  17518. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17519. // Viewport
  17520. engine.setViewport(this.activeCamera.viewport);
  17521. // Camera
  17522. this.resetCachedMaterial();
  17523. this._renderId++;
  17524. this.updateTransformMatrix();
  17525. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17526. // Meshes
  17527. this._evaluateActiveMeshesDuration.beginMonitoring();
  17528. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17529. this._evaluateActiveMeshes();
  17530. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17531. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17532. // Software skinning
  17533. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17534. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17535. mesh.applySkeleton(mesh.skeleton);
  17536. }
  17537. // Render targets
  17538. this._renderTargetsDuration.beginMonitoring();
  17539. var needsRestoreFrameBuffer = false;
  17540. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17541. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  17542. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  17543. }
  17544. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17545. this._intermediateRendering = true;
  17546. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17547. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17548. var renderTarget = this._renderTargets.data[renderIndex];
  17549. if (renderTarget._shouldRender()) {
  17550. this._renderId++;
  17551. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17552. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17553. }
  17554. }
  17555. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17556. this._intermediateRendering = false;
  17557. this._renderId++;
  17558. needsRestoreFrameBuffer = true; // Restore back buffer
  17559. }
  17560. // Render HighlightLayer Texture
  17561. var stencilState = this._engine.getStencilBuffer();
  17562. var renderhighlights = false;
  17563. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17564. this._intermediateRendering = true;
  17565. for (var i = 0; i < this.highlightLayers.length; i++) {
  17566. var highlightLayer = this.highlightLayers[i];
  17567. if (highlightLayer.shouldRender() &&
  17568. (!highlightLayer.camera ||
  17569. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17570. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17571. renderhighlights = true;
  17572. var renderTarget = highlightLayer._mainTexture;
  17573. if (renderTarget._shouldRender()) {
  17574. this._renderId++;
  17575. renderTarget.render(false, false);
  17576. needsRestoreFrameBuffer = true;
  17577. }
  17578. }
  17579. }
  17580. this._intermediateRendering = false;
  17581. this._renderId++;
  17582. }
  17583. if (needsRestoreFrameBuffer) {
  17584. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17585. }
  17586. this._renderTargetsDuration.endMonitoring(false);
  17587. // Prepare Frame
  17588. this.postProcessManager._prepareFrame();
  17589. this._renderDuration.beginMonitoring();
  17590. // Backgrounds
  17591. var layerIndex;
  17592. var layer;
  17593. if (this.layers.length) {
  17594. engine.setDepthBuffer(false);
  17595. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17596. layer = this.layers[layerIndex];
  17597. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17598. layer.render();
  17599. }
  17600. }
  17601. engine.setDepthBuffer(true);
  17602. }
  17603. // Render
  17604. BABYLON.Tools.StartPerformanceCounter("Main render");
  17605. // Activate HighlightLayer stencil
  17606. if (renderhighlights) {
  17607. this._engine.setStencilBuffer(true);
  17608. }
  17609. this._renderingManager.render(null, null, true, true);
  17610. // Restore HighlightLayer stencil
  17611. if (renderhighlights) {
  17612. this._engine.setStencilBuffer(stencilState);
  17613. }
  17614. BABYLON.Tools.EndPerformanceCounter("Main render");
  17615. // Bounding boxes
  17616. if (this._boundingBoxRenderer) {
  17617. this._boundingBoxRenderer.render();
  17618. }
  17619. // Lens flares
  17620. if (this.lensFlaresEnabled) {
  17621. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17622. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17623. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17624. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17625. lensFlareSystem.render();
  17626. }
  17627. }
  17628. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17629. }
  17630. // Foregrounds
  17631. if (this.layers.length) {
  17632. engine.setDepthBuffer(false);
  17633. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17634. layer = this.layers[layerIndex];
  17635. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17636. layer.render();
  17637. }
  17638. }
  17639. engine.setDepthBuffer(true);
  17640. }
  17641. // Highlight Layer
  17642. if (renderhighlights) {
  17643. engine.setDepthBuffer(false);
  17644. for (var i = 0; i < this.highlightLayers.length; i++) {
  17645. if (this.highlightLayers[i].shouldRender()) {
  17646. this.highlightLayers[i].render();
  17647. }
  17648. }
  17649. engine.setDepthBuffer(true);
  17650. }
  17651. this._renderDuration.endMonitoring(false);
  17652. // Finalize frame
  17653. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17654. // Update camera
  17655. this.activeCamera._updateFromScene();
  17656. // Reset some special arrays
  17657. this._renderTargets.reset();
  17658. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17659. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17660. };
  17661. Scene.prototype._processSubCameras = function (camera) {
  17662. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17663. this._renderForCamera(camera);
  17664. return;
  17665. }
  17666. // rig cameras
  17667. for (var index = 0; index < camera._rigCameras.length; index++) {
  17668. this._renderForCamera(camera._rigCameras[index]);
  17669. }
  17670. this.activeCamera = camera;
  17671. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17672. // Update camera
  17673. this.activeCamera._updateFromScene();
  17674. };
  17675. Scene.prototype._checkIntersections = function () {
  17676. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17677. var sourceMesh = this._meshesForIntersections.data[index];
  17678. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17679. var action = sourceMesh.actionManager.actions[actionIndex];
  17680. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17681. var parameters = action.getTriggerParameter();
  17682. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17683. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17684. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17685. if (areIntersecting && currentIntersectionInProgress === -1) {
  17686. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17687. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17688. sourceMesh._intersectionsInProgress.push(otherMesh);
  17689. }
  17690. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17691. sourceMesh._intersectionsInProgress.push(otherMesh);
  17692. }
  17693. }
  17694. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17695. //They intersected, and now they don't.
  17696. //is this trigger an exit trigger? execute an event.
  17697. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17698. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17699. }
  17700. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17701. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17702. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17703. }
  17704. }
  17705. }
  17706. }
  17707. }
  17708. };
  17709. Scene.prototype.render = function () {
  17710. if (this.isDisposed) {
  17711. return;
  17712. }
  17713. this._lastFrameDuration.beginMonitoring();
  17714. this._particlesDuration.fetchNewFrame();
  17715. this._spritesDuration.fetchNewFrame();
  17716. this._activeParticles.fetchNewFrame();
  17717. this._renderDuration.fetchNewFrame();
  17718. this._renderTargetsDuration.fetchNewFrame();
  17719. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17720. this._totalVertices.fetchNewFrame();
  17721. this._activeIndices.fetchNewFrame();
  17722. this._activeBones.fetchNewFrame();
  17723. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17724. this._meshesForIntersections.reset();
  17725. this.resetCachedMaterial();
  17726. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17727. // Actions
  17728. if (this.actionManager) {
  17729. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17730. }
  17731. //Simplification Queue
  17732. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17733. this.simplificationQueue.executeNext();
  17734. }
  17735. // Animations
  17736. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17737. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17738. this._animate();
  17739. // Physics
  17740. if (this._physicsEngine) {
  17741. BABYLON.Tools.StartPerformanceCounter("Physics");
  17742. this._physicsEngine._step(deltaTime / 1000.0);
  17743. BABYLON.Tools.EndPerformanceCounter("Physics");
  17744. }
  17745. // Before render
  17746. this.onBeforeRenderObservable.notifyObservers(this);
  17747. // Customs render targets
  17748. this._renderTargetsDuration.beginMonitoring();
  17749. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17750. var engine = this.getEngine();
  17751. var currentActiveCamera = this.activeCamera;
  17752. if (this.renderTargetsEnabled) {
  17753. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17754. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17755. var renderTarget = this.customRenderTargets[customIndex];
  17756. if (renderTarget._shouldRender()) {
  17757. this._renderId++;
  17758. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17759. if (!this.activeCamera)
  17760. throw new Error("Active camera not set");
  17761. // Viewport
  17762. engine.setViewport(this.activeCamera.viewport);
  17763. // Camera
  17764. this.updateTransformMatrix();
  17765. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17766. }
  17767. }
  17768. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17769. this._renderId++;
  17770. }
  17771. // Restore back buffer
  17772. if (this.customRenderTargets.length > 0) {
  17773. engine.restoreDefaultFramebuffer();
  17774. }
  17775. this._renderTargetsDuration.endMonitoring();
  17776. this.activeCamera = currentActiveCamera;
  17777. // Procedural textures
  17778. if (this.proceduralTexturesEnabled) {
  17779. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17780. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17781. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17782. if (proceduralTexture._shouldRender()) {
  17783. proceduralTexture.render();
  17784. }
  17785. }
  17786. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17787. }
  17788. // Clear
  17789. if (this.autoClearDepthAndStencil || this.autoClear) {
  17790. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17791. }
  17792. // Shadows
  17793. if (this.shadowsEnabled) {
  17794. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17795. var light = this.lights[lightIndex];
  17796. var shadowGenerator = light.getShadowGenerator();
  17797. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17798. var shadowMap = shadowGenerator.getShadowMap();
  17799. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17800. this._renderTargets.push(shadowMap);
  17801. }
  17802. }
  17803. }
  17804. }
  17805. // Depth renderer
  17806. if (this._depthRenderer) {
  17807. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17808. }
  17809. // Geometry renderer
  17810. if (this._geometryBufferRenderer) {
  17811. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17812. }
  17813. // RenderPipeline
  17814. if (this._postProcessRenderPipelineManager) {
  17815. this._postProcessRenderPipelineManager.update();
  17816. }
  17817. // Multi-cameras?
  17818. if (this.activeCameras.length > 0) {
  17819. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17820. if (cameraIndex > 0) {
  17821. this._engine.clear(null, false, true, true);
  17822. }
  17823. this._processSubCameras(this.activeCameras[cameraIndex]);
  17824. }
  17825. }
  17826. else {
  17827. if (!this.activeCamera) {
  17828. throw new Error("No camera defined");
  17829. }
  17830. this._processSubCameras(this.activeCamera);
  17831. }
  17832. // Intersection checks
  17833. this._checkIntersections();
  17834. // Update the audio listener attached to the camera
  17835. if (BABYLON.AudioEngine) {
  17836. this._updateAudioParameters();
  17837. }
  17838. // After render
  17839. if (this.afterRender) {
  17840. this.afterRender();
  17841. }
  17842. this.onAfterRenderObservable.notifyObservers(this);
  17843. // Cleaning
  17844. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17845. this._toBeDisposed.data[index].dispose();
  17846. this._toBeDisposed[index] = null;
  17847. }
  17848. this._toBeDisposed.reset();
  17849. if (this.dumpNextRenderTargets) {
  17850. this.dumpNextRenderTargets = false;
  17851. }
  17852. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17853. this._lastFrameDuration.endMonitoring();
  17854. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17855. this._totalLightsCounter.addCount(this.lights.length, true);
  17856. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17857. this._totalTexturesCounter.addCount(this.textures.length, true);
  17858. this._activeBones.addCount(0, true);
  17859. this._activeIndices.addCount(0, true);
  17860. this._activeParticles.addCount(0, true);
  17861. };
  17862. Scene.prototype._updateAudioParameters = function () {
  17863. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17864. return;
  17865. }
  17866. var listeningCamera;
  17867. var audioEngine = BABYLON.Engine.audioEngine;
  17868. if (this.activeCameras.length > 0) {
  17869. listeningCamera = this.activeCameras[0];
  17870. }
  17871. else {
  17872. listeningCamera = this.activeCamera;
  17873. }
  17874. if (listeningCamera && audioEngine.canUseWebAudio) {
  17875. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17876. // for VR cameras
  17877. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  17878. listeningCamera = listeningCamera.rigCameras[0];
  17879. }
  17880. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17881. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17882. cameraDirection.normalize();
  17883. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17884. var i;
  17885. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17886. var sound = this.mainSoundTrack.soundCollection[i];
  17887. if (sound.useCustomAttenuation) {
  17888. sound.updateDistanceFromListener();
  17889. }
  17890. }
  17891. for (i = 0; i < this.soundTracks.length; i++) {
  17892. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17893. sound = this.soundTracks[i].soundCollection[j];
  17894. if (sound.useCustomAttenuation) {
  17895. sound.updateDistanceFromListener();
  17896. }
  17897. }
  17898. }
  17899. }
  17900. };
  17901. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17902. // Audio
  17903. get: function () {
  17904. return this._audioEnabled;
  17905. },
  17906. set: function (value) {
  17907. this._audioEnabled = value;
  17908. if (BABYLON.AudioEngine) {
  17909. if (this._audioEnabled) {
  17910. this._enableAudio();
  17911. }
  17912. else {
  17913. this._disableAudio();
  17914. }
  17915. }
  17916. },
  17917. enumerable: true,
  17918. configurable: true
  17919. });
  17920. Scene.prototype._disableAudio = function () {
  17921. var i;
  17922. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17923. this.mainSoundTrack.soundCollection[i].pause();
  17924. }
  17925. for (i = 0; i < this.soundTracks.length; i++) {
  17926. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17927. this.soundTracks[i].soundCollection[j].pause();
  17928. }
  17929. }
  17930. };
  17931. Scene.prototype._enableAudio = function () {
  17932. var i;
  17933. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17934. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17935. this.mainSoundTrack.soundCollection[i].play();
  17936. }
  17937. }
  17938. for (i = 0; i < this.soundTracks.length; i++) {
  17939. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17940. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17941. this.soundTracks[i].soundCollection[j].play();
  17942. }
  17943. }
  17944. }
  17945. };
  17946. Object.defineProperty(Scene.prototype, "headphone", {
  17947. get: function () {
  17948. return this._headphone;
  17949. },
  17950. set: function (value) {
  17951. this._headphone = value;
  17952. if (BABYLON.AudioEngine) {
  17953. if (this._headphone) {
  17954. this._switchAudioModeForHeadphones();
  17955. }
  17956. else {
  17957. this._switchAudioModeForNormalSpeakers();
  17958. }
  17959. }
  17960. },
  17961. enumerable: true,
  17962. configurable: true
  17963. });
  17964. Scene.prototype._switchAudioModeForHeadphones = function () {
  17965. this.mainSoundTrack.switchPanningModelToHRTF();
  17966. for (var i = 0; i < this.soundTracks.length; i++) {
  17967. this.soundTracks[i].switchPanningModelToHRTF();
  17968. }
  17969. };
  17970. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17971. this.mainSoundTrack.switchPanningModelToEqualPower();
  17972. for (var i = 0; i < this.soundTracks.length; i++) {
  17973. this.soundTracks[i].switchPanningModelToEqualPower();
  17974. }
  17975. };
  17976. Scene.prototype.enableDepthRenderer = function () {
  17977. if (this._depthRenderer) {
  17978. return this._depthRenderer;
  17979. }
  17980. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17981. return this._depthRenderer;
  17982. };
  17983. Scene.prototype.disableDepthRenderer = function () {
  17984. if (!this._depthRenderer) {
  17985. return;
  17986. }
  17987. this._depthRenderer.dispose();
  17988. this._depthRenderer = null;
  17989. };
  17990. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  17991. if (ratio === void 0) { ratio = 1; }
  17992. if (this._geometryBufferRenderer) {
  17993. return this._geometryBufferRenderer;
  17994. }
  17995. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  17996. if (!this._geometryBufferRenderer.isSupported) {
  17997. this._geometryBufferRenderer = null;
  17998. }
  17999. return this._geometryBufferRenderer;
  18000. };
  18001. Scene.prototype.disableGeometryBufferRenderer = function () {
  18002. if (!this._geometryBufferRenderer) {
  18003. return;
  18004. }
  18005. this._geometryBufferRenderer.dispose();
  18006. this._geometryBufferRenderer = null;
  18007. };
  18008. Scene.prototype.freezeMaterials = function () {
  18009. for (var i = 0; i < this.materials.length; i++) {
  18010. this.materials[i].freeze();
  18011. }
  18012. };
  18013. Scene.prototype.unfreezeMaterials = function () {
  18014. for (var i = 0; i < this.materials.length; i++) {
  18015. this.materials[i].unfreeze();
  18016. }
  18017. };
  18018. Scene.prototype.dispose = function () {
  18019. this.beforeRender = null;
  18020. this.afterRender = null;
  18021. this.skeletons = [];
  18022. this.morphTargetManagers = [];
  18023. this.importedMeshesFiles = new Array();
  18024. if (this._depthRenderer) {
  18025. this._depthRenderer.dispose();
  18026. }
  18027. // Smart arrays
  18028. if (this.activeCamera) {
  18029. this.activeCamera._activeMeshes.dispose();
  18030. this.activeCamera = null;
  18031. }
  18032. this._activeMeshes.dispose();
  18033. this._renderingManager.dispose();
  18034. this._processedMaterials.dispose();
  18035. this._activeParticleSystems.dispose();
  18036. this._activeSkeletons.dispose();
  18037. this._softwareSkinnedMeshes.dispose();
  18038. if (this._boundingBoxRenderer) {
  18039. this._boundingBoxRenderer.dispose();
  18040. }
  18041. this._meshesForIntersections.dispose();
  18042. this._toBeDisposed.dispose();
  18043. // Debug layer
  18044. if (this._debugLayer) {
  18045. this._debugLayer.hide();
  18046. }
  18047. // Events
  18048. this.onDisposeObservable.notifyObservers(this);
  18049. this.onDisposeObservable.clear();
  18050. this.onBeforeRenderObservable.clear();
  18051. this.onAfterRenderObservable.clear();
  18052. this.detachControl();
  18053. // Release sounds & sounds tracks
  18054. if (BABYLON.AudioEngine) {
  18055. this.disposeSounds();
  18056. }
  18057. // Detach cameras
  18058. var canvas = this._engine.getRenderingCanvas();
  18059. var index;
  18060. for (index = 0; index < this.cameras.length; index++) {
  18061. this.cameras[index].detachControl(canvas);
  18062. }
  18063. // Release lights
  18064. while (this.lights.length) {
  18065. this.lights[0].dispose();
  18066. }
  18067. // Release meshes
  18068. while (this.meshes.length) {
  18069. this.meshes[0].dispose(true);
  18070. }
  18071. // Release cameras
  18072. while (this.cameras.length) {
  18073. this.cameras[0].dispose();
  18074. }
  18075. // Release materials
  18076. while (this.materials.length) {
  18077. this.materials[0].dispose();
  18078. }
  18079. // Release particles
  18080. while (this.particleSystems.length) {
  18081. this.particleSystems[0].dispose();
  18082. }
  18083. // Release sprites
  18084. while (this.spriteManagers.length) {
  18085. this.spriteManagers[0].dispose();
  18086. }
  18087. // Release layers
  18088. while (this.layers.length) {
  18089. this.layers[0].dispose();
  18090. }
  18091. while (this.highlightLayers.length) {
  18092. this.highlightLayers[0].dispose();
  18093. }
  18094. // Release textures
  18095. while (this.textures.length) {
  18096. this.textures[0].dispose();
  18097. }
  18098. // Release UBO
  18099. this._sceneUbo.dispose();
  18100. // Post-processes
  18101. this.postProcessManager.dispose();
  18102. // Physics
  18103. if (this._physicsEngine) {
  18104. this.disablePhysicsEngine();
  18105. }
  18106. // Remove from engine
  18107. index = this._engine.scenes.indexOf(this);
  18108. if (index > -1) {
  18109. this._engine.scenes.splice(index, 1);
  18110. }
  18111. this._engine.wipeCaches();
  18112. this._engine = null;
  18113. };
  18114. Object.defineProperty(Scene.prototype, "isDisposed", {
  18115. get: function () {
  18116. return !this._engine;
  18117. },
  18118. enumerable: true,
  18119. configurable: true
  18120. });
  18121. // Release sounds & sounds tracks
  18122. Scene.prototype.disposeSounds = function () {
  18123. this.mainSoundTrack.dispose();
  18124. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18125. this.soundTracks[scIndex].dispose();
  18126. }
  18127. };
  18128. // Octrees
  18129. Scene.prototype.getWorldExtends = function () {
  18130. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18131. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18132. for (var index = 0; index < this.meshes.length; index++) {
  18133. var mesh = this.meshes[index];
  18134. mesh.computeWorldMatrix(true);
  18135. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18136. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18137. BABYLON.Tools.CheckExtends(minBox, min, max);
  18138. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18139. }
  18140. return {
  18141. min: min,
  18142. max: max
  18143. };
  18144. };
  18145. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18146. if (maxCapacity === void 0) { maxCapacity = 64; }
  18147. if (maxDepth === void 0) { maxDepth = 2; }
  18148. if (!this._selectionOctree) {
  18149. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18150. }
  18151. var worldExtends = this.getWorldExtends();
  18152. // Update octree
  18153. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18154. return this._selectionOctree;
  18155. };
  18156. // Picking
  18157. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18158. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18159. var engine = this._engine;
  18160. if (!camera) {
  18161. if (!this.activeCamera)
  18162. throw new Error("Active camera not set");
  18163. camera = this.activeCamera;
  18164. }
  18165. var cameraViewport = camera.viewport;
  18166. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18167. // Moving coordinates to local viewport world
  18168. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18169. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18170. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18171. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18172. };
  18173. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18174. if (!BABYLON.PickingInfo) {
  18175. return null;
  18176. }
  18177. var engine = this._engine;
  18178. if (!camera) {
  18179. if (!this.activeCamera)
  18180. throw new Error("Active camera not set");
  18181. camera = this.activeCamera;
  18182. }
  18183. var cameraViewport = camera.viewport;
  18184. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18185. var identity = BABYLON.Matrix.Identity();
  18186. // Moving coordinates to local viewport world
  18187. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18188. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18189. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18190. };
  18191. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18192. if (!BABYLON.PickingInfo) {
  18193. return null;
  18194. }
  18195. var pickingInfo = null;
  18196. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18197. var mesh = this.meshes[meshIndex];
  18198. if (predicate) {
  18199. if (!predicate(mesh)) {
  18200. continue;
  18201. }
  18202. }
  18203. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18204. continue;
  18205. }
  18206. var world = mesh.getWorldMatrix();
  18207. var ray = rayFunction(world);
  18208. var result = mesh.intersects(ray, fastCheck);
  18209. if (!result || !result.hit)
  18210. continue;
  18211. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18212. continue;
  18213. pickingInfo = result;
  18214. if (fastCheck) {
  18215. break;
  18216. }
  18217. }
  18218. return pickingInfo || new BABYLON.PickingInfo();
  18219. };
  18220. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18221. if (!BABYLON.PickingInfo) {
  18222. return null;
  18223. }
  18224. var pickingInfos = new Array();
  18225. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18226. var mesh = this.meshes[meshIndex];
  18227. if (predicate) {
  18228. if (!predicate(mesh)) {
  18229. continue;
  18230. }
  18231. }
  18232. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18233. continue;
  18234. }
  18235. var world = mesh.getWorldMatrix();
  18236. var ray = rayFunction(world);
  18237. var result = mesh.intersects(ray, false);
  18238. if (!result || !result.hit)
  18239. continue;
  18240. pickingInfos.push(result);
  18241. }
  18242. return pickingInfos;
  18243. };
  18244. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18245. if (!BABYLON.PickingInfo) {
  18246. return null;
  18247. }
  18248. var pickingInfo = null;
  18249. camera = camera || this.activeCamera;
  18250. if (this.spriteManagers.length > 0) {
  18251. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18252. var spriteManager = this.spriteManagers[spriteIndex];
  18253. if (!spriteManager.isPickable) {
  18254. continue;
  18255. }
  18256. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18257. if (!result || !result.hit)
  18258. continue;
  18259. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18260. continue;
  18261. pickingInfo = result;
  18262. if (fastCheck) {
  18263. break;
  18264. }
  18265. }
  18266. }
  18267. return pickingInfo || new BABYLON.PickingInfo();
  18268. };
  18269. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18270. /// <param name="x">X position on screen</param>
  18271. /// <param name="y">Y position on screen</param>
  18272. /// <param name="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</param>
  18273. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18274. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  18275. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18276. var _this = this;
  18277. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18278. };
  18279. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18280. /// <param name="x">X position on screen</param>
  18281. /// <param name="y">Y position on screen</param>
  18282. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  18283. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18284. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  18285. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18286. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18287. };
  18288. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18289. var _this = this;
  18290. return this._internalPick(function (world) {
  18291. if (!_this._pickWithRayInverseMatrix) {
  18292. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18293. }
  18294. world.invertToRef(_this._pickWithRayInverseMatrix);
  18295. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18296. }, predicate, fastCheck);
  18297. };
  18298. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18299. /// <param name="x">X position on screen</param>
  18300. /// <param name="y">Y position on screen</param>
  18301. /// <param name="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</param>
  18302. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  18303. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18304. var _this = this;
  18305. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18306. };
  18307. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18308. /// <param name="ray">Ray to use</param>
  18309. /// <param name="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</param>
  18310. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18311. var _this = this;
  18312. return this._internalMultiPick(function (world) {
  18313. if (!_this._pickWithRayInverseMatrix) {
  18314. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18315. }
  18316. world.invertToRef(_this._pickWithRayInverseMatrix);
  18317. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18318. }, predicate);
  18319. };
  18320. Scene.prototype.setPointerOverMesh = function (mesh) {
  18321. if (this._pointerOverMesh === mesh) {
  18322. return;
  18323. }
  18324. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18325. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18326. }
  18327. this._pointerOverMesh = mesh;
  18328. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18329. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18330. }
  18331. };
  18332. Scene.prototype.getPointerOverMesh = function () {
  18333. return this._pointerOverMesh;
  18334. };
  18335. Scene.prototype.setPointerOverSprite = function (sprite) {
  18336. if (this._pointerOverSprite === sprite) {
  18337. return;
  18338. }
  18339. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18340. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18341. }
  18342. this._pointerOverSprite = sprite;
  18343. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18344. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18345. }
  18346. };
  18347. Scene.prototype.getPointerOverSprite = function () {
  18348. return this._pointerOverSprite;
  18349. };
  18350. // Physics
  18351. Scene.prototype.getPhysicsEngine = function () {
  18352. return this._physicsEngine;
  18353. };
  18354. /**
  18355. * Enables physics to the current scene
  18356. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18357. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18358. * @return {boolean} was the physics engine initialized
  18359. */
  18360. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18361. if (this._physicsEngine) {
  18362. return true;
  18363. }
  18364. try {
  18365. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18366. return true;
  18367. }
  18368. catch (e) {
  18369. BABYLON.Tools.Error(e.message);
  18370. return false;
  18371. }
  18372. };
  18373. Scene.prototype.disablePhysicsEngine = function () {
  18374. if (!this._physicsEngine) {
  18375. return;
  18376. }
  18377. this._physicsEngine.dispose();
  18378. this._physicsEngine = undefined;
  18379. };
  18380. Scene.prototype.isPhysicsEnabled = function () {
  18381. return this._physicsEngine !== undefined;
  18382. };
  18383. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18384. var mesh = compound.parts[0].mesh;
  18385. mesh.physicsImpostor.dispose();
  18386. mesh.physicsImpostor = null;
  18387. };
  18388. // Misc.
  18389. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18390. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18391. // Light
  18392. if (this.lights.length === 0) {
  18393. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18394. }
  18395. // Camera
  18396. if (!this.activeCamera) {
  18397. var worldExtends = this.getWorldExtends();
  18398. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18399. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18400. var camera;
  18401. var radius = worldSize.length() * 1.5;
  18402. if (createArcRotateCamera) {
  18403. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18404. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18405. arcRotateCamera.wheelPrecision = 100 / radius;
  18406. camera = arcRotateCamera;
  18407. }
  18408. else {
  18409. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18410. freeCamera.setTarget(worldCenter);
  18411. camera = freeCamera;
  18412. }
  18413. camera.minZ = radius * 0.01;
  18414. camera.maxZ = radius * 100;
  18415. camera.speed = radius * 0.2;
  18416. this.activeCamera = camera;
  18417. }
  18418. };
  18419. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr) {
  18420. if (pbr === void 0) { pbr = false; }
  18421. if (environmentTexture) {
  18422. this.environmentTexture = environmentTexture;
  18423. }
  18424. if (!this.environmentTexture) {
  18425. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18426. return;
  18427. }
  18428. if (!this.environmentTexture) {
  18429. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18430. return;
  18431. }
  18432. // Skybox
  18433. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, this);
  18434. if (pbr) {
  18435. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18436. hdrSkyboxMaterial.backFaceCulling = false;
  18437. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18438. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18439. hdrSkyboxMaterial.microSurface = 1.0;
  18440. hdrSkyboxMaterial.disableLighting = true;
  18441. hdrSkybox.infiniteDistance = true;
  18442. hdrSkybox.material = hdrSkyboxMaterial;
  18443. }
  18444. else {
  18445. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18446. skyboxMaterial.backFaceCulling = false;
  18447. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18448. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18449. skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
  18450. skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
  18451. skyboxMaterial.disableLighting = true;
  18452. hdrSkybox.infiniteDistance = true;
  18453. hdrSkybox.material = skyboxMaterial;
  18454. }
  18455. return hdrSkybox;
  18456. };
  18457. // Tags
  18458. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18459. if (tagsQuery === undefined) {
  18460. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18461. return list;
  18462. }
  18463. var listByTags = [];
  18464. forEach = forEach || (function (item) { return; });
  18465. for (var i in list) {
  18466. var item = list[i];
  18467. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18468. listByTags.push(item);
  18469. forEach(item);
  18470. }
  18471. }
  18472. return listByTags;
  18473. };
  18474. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18475. return this._getByTags(this.meshes, tagsQuery, forEach);
  18476. };
  18477. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18478. return this._getByTags(this.cameras, tagsQuery, forEach);
  18479. };
  18480. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18481. return this._getByTags(this.lights, tagsQuery, forEach);
  18482. };
  18483. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18484. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18485. };
  18486. /**
  18487. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18488. * This allowed control for front to back rendering or reversly depending of the special needs.
  18489. *
  18490. * @param renderingGroupId The rendering group id corresponding to its index
  18491. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18492. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18493. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18494. */
  18495. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18496. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18497. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18498. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18499. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18500. };
  18501. /**
  18502. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18503. *
  18504. * @param renderingGroupId The rendering group id corresponding to its index
  18505. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18506. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18507. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18508. */
  18509. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18510. if (depth === void 0) { depth = true; }
  18511. if (stencil === void 0) { stencil = true; }
  18512. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18513. };
  18514. /**
  18515. * Will flag all materials as dirty to trigger new shader compilation
  18516. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18517. */
  18518. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18519. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18520. var material = _a[_i];
  18521. if (predicate && !predicate(material)) {
  18522. continue;
  18523. }
  18524. material.markAsDirty(flag);
  18525. }
  18526. };
  18527. return Scene;
  18528. }());
  18529. // Statics
  18530. Scene._FOGMODE_NONE = 0;
  18531. Scene._FOGMODE_EXP = 1;
  18532. Scene._FOGMODE_EXP2 = 2;
  18533. Scene._FOGMODE_LINEAR = 3;
  18534. Scene.MinDeltaTime = 1.0;
  18535. Scene.MaxDeltaTime = 1000.0;
  18536. Scene.DragMovementThreshold = 10; // in pixels
  18537. Scene.LongPressDelay = 500; // in milliseconds
  18538. Scene.DoubleClickDelay = 300; // in milliseconds
  18539. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18540. BABYLON.Scene = Scene;
  18541. })(BABYLON || (BABYLON = {}));
  18542. //# sourceMappingURL=babylon.scene.js.map
  18543. var BABYLON;
  18544. (function (BABYLON) {
  18545. var Buffer = (function () {
  18546. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18547. if (engine instanceof BABYLON.Mesh) {
  18548. this._engine = engine.getScene().getEngine();
  18549. }
  18550. else {
  18551. this._engine = engine;
  18552. }
  18553. this._updatable = updatable;
  18554. this._data = data;
  18555. this._strideSize = stride;
  18556. if (!postponeInternalCreation) {
  18557. this.create();
  18558. }
  18559. this._instanced = instanced;
  18560. this._instanceDivisor = instanced ? 1 : 0;
  18561. }
  18562. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18563. // a lot of these parameters are ignored as they are overriden by the buffer
  18564. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18565. };
  18566. // Properties
  18567. Buffer.prototype.isUpdatable = function () {
  18568. return this._updatable;
  18569. };
  18570. Buffer.prototype.getData = function () {
  18571. return this._data;
  18572. };
  18573. Buffer.prototype.getBuffer = function () {
  18574. return this._buffer;
  18575. };
  18576. Buffer.prototype.getStrideSize = function () {
  18577. return this._strideSize;
  18578. };
  18579. Buffer.prototype.getIsInstanced = function () {
  18580. return this._instanced;
  18581. };
  18582. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  18583. get: function () {
  18584. return this._instanceDivisor;
  18585. },
  18586. set: function (value) {
  18587. this._instanceDivisor = value;
  18588. if (value == 0) {
  18589. this._instanced = false;
  18590. }
  18591. else {
  18592. this._instanced = true;
  18593. }
  18594. },
  18595. enumerable: true,
  18596. configurable: true
  18597. });
  18598. // Methods
  18599. Buffer.prototype.create = function (data) {
  18600. if (!data && this._buffer) {
  18601. return; // nothing to do
  18602. }
  18603. data = data || this._data;
  18604. if (!this._buffer) {
  18605. if (this._updatable) {
  18606. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18607. this._data = data;
  18608. }
  18609. else {
  18610. this._buffer = this._engine.createVertexBuffer(data);
  18611. }
  18612. }
  18613. else if (this._updatable) {
  18614. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18615. this._data = data;
  18616. }
  18617. };
  18618. Buffer.prototype.update = function (data) {
  18619. this.create(data);
  18620. };
  18621. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18622. if (!this._buffer) {
  18623. return;
  18624. }
  18625. if (this._updatable) {
  18626. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18627. this._data = null;
  18628. }
  18629. };
  18630. Buffer.prototype.dispose = function () {
  18631. if (!this._buffer) {
  18632. return;
  18633. }
  18634. if (this._engine._releaseBuffer(this._buffer)) {
  18635. this._buffer = null;
  18636. }
  18637. };
  18638. return Buffer;
  18639. }());
  18640. BABYLON.Buffer = Buffer;
  18641. })(BABYLON || (BABYLON = {}));
  18642. //# sourceMappingURL=babylon.buffer.js.map
  18643. var BABYLON;
  18644. (function (BABYLON) {
  18645. var VertexBuffer = (function () {
  18646. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18647. if (!stride) {
  18648. // Deduce stride from kind
  18649. switch (kind) {
  18650. case VertexBuffer.PositionKind:
  18651. stride = 3;
  18652. break;
  18653. case VertexBuffer.NormalKind:
  18654. stride = 3;
  18655. break;
  18656. case VertexBuffer.UVKind:
  18657. case VertexBuffer.UV2Kind:
  18658. case VertexBuffer.UV3Kind:
  18659. case VertexBuffer.UV4Kind:
  18660. case VertexBuffer.UV5Kind:
  18661. case VertexBuffer.UV6Kind:
  18662. stride = 2;
  18663. break;
  18664. case VertexBuffer.TangentKind:
  18665. case VertexBuffer.ColorKind:
  18666. stride = 4;
  18667. break;
  18668. case VertexBuffer.MatricesIndicesKind:
  18669. case VertexBuffer.MatricesIndicesExtraKind:
  18670. stride = 4;
  18671. break;
  18672. case VertexBuffer.MatricesWeightsKind:
  18673. case VertexBuffer.MatricesWeightsExtraKind:
  18674. stride = 4;
  18675. break;
  18676. }
  18677. }
  18678. if (data instanceof BABYLON.Buffer) {
  18679. if (!stride) {
  18680. stride = data.getStrideSize();
  18681. }
  18682. this._buffer = data;
  18683. this._ownsBuffer = false;
  18684. }
  18685. else {
  18686. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18687. this._ownsBuffer = true;
  18688. }
  18689. this._stride = stride;
  18690. this._offset = offset ? offset : 0;
  18691. this._size = size ? size : stride;
  18692. this._kind = kind;
  18693. }
  18694. /**
  18695. * Returns the kind of the VertexBuffer (string).
  18696. */
  18697. VertexBuffer.prototype.getKind = function () {
  18698. return this._kind;
  18699. };
  18700. // Properties
  18701. /**
  18702. * Boolean : is the VertexBuffer updatable ?
  18703. */
  18704. VertexBuffer.prototype.isUpdatable = function () {
  18705. return this._buffer.isUpdatable();
  18706. };
  18707. /**
  18708. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18709. */
  18710. VertexBuffer.prototype.getData = function () {
  18711. return this._buffer.getData();
  18712. };
  18713. /**
  18714. * Returns the WebGLBuffer associated to the VertexBuffer.
  18715. */
  18716. VertexBuffer.prototype.getBuffer = function () {
  18717. return this._buffer.getBuffer();
  18718. };
  18719. /**
  18720. * Returns the stride of the VertexBuffer (integer).
  18721. */
  18722. VertexBuffer.prototype.getStrideSize = function () {
  18723. return this._stride;
  18724. };
  18725. /**
  18726. * Returns the offset (integer).
  18727. */
  18728. VertexBuffer.prototype.getOffset = function () {
  18729. return this._offset;
  18730. };
  18731. /**
  18732. * Returns the VertexBuffer total size (integer).
  18733. */
  18734. VertexBuffer.prototype.getSize = function () {
  18735. return this._size;
  18736. };
  18737. /**
  18738. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18739. */
  18740. VertexBuffer.prototype.getIsInstanced = function () {
  18741. return this._buffer.getIsInstanced();
  18742. };
  18743. /**
  18744. * Returns the instancing divisor, zero for non-instanced (integer).
  18745. */
  18746. VertexBuffer.prototype.getInstanceDivisor = function () {
  18747. return this._buffer.instanceDivisor;
  18748. };
  18749. // Methods
  18750. /**
  18751. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18752. * Returns the created WebGLBuffer.
  18753. */
  18754. VertexBuffer.prototype.create = function (data) {
  18755. return this._buffer.create(data);
  18756. };
  18757. /**
  18758. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18759. * Returns the updated WebGLBuffer.
  18760. */
  18761. VertexBuffer.prototype.update = function (data) {
  18762. return this._buffer.update(data);
  18763. };
  18764. /**
  18765. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18766. * Returns the directly updated WebGLBuffer.
  18767. */
  18768. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18769. return this._buffer.updateDirectly(data, offset);
  18770. };
  18771. /**
  18772. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18773. */
  18774. VertexBuffer.prototype.dispose = function () {
  18775. if (this._ownsBuffer) {
  18776. this._buffer.dispose();
  18777. }
  18778. };
  18779. Object.defineProperty(VertexBuffer, "PositionKind", {
  18780. get: function () {
  18781. return VertexBuffer._PositionKind;
  18782. },
  18783. enumerable: true,
  18784. configurable: true
  18785. });
  18786. Object.defineProperty(VertexBuffer, "NormalKind", {
  18787. get: function () {
  18788. return VertexBuffer._NormalKind;
  18789. },
  18790. enumerable: true,
  18791. configurable: true
  18792. });
  18793. Object.defineProperty(VertexBuffer, "TangentKind", {
  18794. get: function () {
  18795. return VertexBuffer._TangentKind;
  18796. },
  18797. enumerable: true,
  18798. configurable: true
  18799. });
  18800. Object.defineProperty(VertexBuffer, "UVKind", {
  18801. get: function () {
  18802. return VertexBuffer._UVKind;
  18803. },
  18804. enumerable: true,
  18805. configurable: true
  18806. });
  18807. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18808. get: function () {
  18809. return VertexBuffer._UV2Kind;
  18810. },
  18811. enumerable: true,
  18812. configurable: true
  18813. });
  18814. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18815. get: function () {
  18816. return VertexBuffer._UV3Kind;
  18817. },
  18818. enumerable: true,
  18819. configurable: true
  18820. });
  18821. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18822. get: function () {
  18823. return VertexBuffer._UV4Kind;
  18824. },
  18825. enumerable: true,
  18826. configurable: true
  18827. });
  18828. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18829. get: function () {
  18830. return VertexBuffer._UV5Kind;
  18831. },
  18832. enumerable: true,
  18833. configurable: true
  18834. });
  18835. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18836. get: function () {
  18837. return VertexBuffer._UV6Kind;
  18838. },
  18839. enumerable: true,
  18840. configurable: true
  18841. });
  18842. Object.defineProperty(VertexBuffer, "ColorKind", {
  18843. get: function () {
  18844. return VertexBuffer._ColorKind;
  18845. },
  18846. enumerable: true,
  18847. configurable: true
  18848. });
  18849. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18850. get: function () {
  18851. return VertexBuffer._MatricesIndicesKind;
  18852. },
  18853. enumerable: true,
  18854. configurable: true
  18855. });
  18856. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18857. get: function () {
  18858. return VertexBuffer._MatricesWeightsKind;
  18859. },
  18860. enumerable: true,
  18861. configurable: true
  18862. });
  18863. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18864. get: function () {
  18865. return VertexBuffer._MatricesIndicesExtraKind;
  18866. },
  18867. enumerable: true,
  18868. configurable: true
  18869. });
  18870. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18871. get: function () {
  18872. return VertexBuffer._MatricesWeightsExtraKind;
  18873. },
  18874. enumerable: true,
  18875. configurable: true
  18876. });
  18877. return VertexBuffer;
  18878. }());
  18879. // Enums
  18880. VertexBuffer._PositionKind = "position";
  18881. VertexBuffer._NormalKind = "normal";
  18882. VertexBuffer._TangentKind = "tangent";
  18883. VertexBuffer._UVKind = "uv";
  18884. VertexBuffer._UV2Kind = "uv2";
  18885. VertexBuffer._UV3Kind = "uv3";
  18886. VertexBuffer._UV4Kind = "uv4";
  18887. VertexBuffer._UV5Kind = "uv5";
  18888. VertexBuffer._UV6Kind = "uv6";
  18889. VertexBuffer._ColorKind = "color";
  18890. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18891. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18892. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18893. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18894. BABYLON.VertexBuffer = VertexBuffer;
  18895. })(BABYLON || (BABYLON = {}));
  18896. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18897. var BABYLON;
  18898. (function (BABYLON) {
  18899. var BaseTexture = (function () {
  18900. function BaseTexture(scene) {
  18901. this._hasAlpha = false;
  18902. this.getAlphaFromRGB = false;
  18903. this.level = 1;
  18904. this.coordinatesIndex = 0;
  18905. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18906. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18907. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18908. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18909. this.isCube = false;
  18910. this.isRenderTarget = false;
  18911. this.animations = new Array();
  18912. /**
  18913. * An event triggered when the texture is disposed.
  18914. * @type {BABYLON.Observable}
  18915. */
  18916. this.onDisposeObservable = new BABYLON.Observable();
  18917. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18918. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18919. this._scene.textures.push(this);
  18920. this._uid = null;
  18921. }
  18922. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18923. get: function () {
  18924. return this._hasAlpha;
  18925. },
  18926. set: function (value) {
  18927. if (this._hasAlpha === value) {
  18928. return;
  18929. }
  18930. this._hasAlpha = value;
  18931. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18932. },
  18933. enumerable: true,
  18934. configurable: true
  18935. });
  18936. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18937. get: function () {
  18938. return this._coordinatesMode;
  18939. },
  18940. set: function (value) {
  18941. if (this._coordinatesMode === value) {
  18942. return;
  18943. }
  18944. this._coordinatesMode = value;
  18945. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18946. },
  18947. enumerable: true,
  18948. configurable: true
  18949. });
  18950. Object.defineProperty(BaseTexture.prototype, "uid", {
  18951. get: function () {
  18952. if (!this._uid) {
  18953. this._uid = BABYLON.Tools.RandomId();
  18954. }
  18955. return this._uid;
  18956. },
  18957. enumerable: true,
  18958. configurable: true
  18959. });
  18960. BaseTexture.prototype.toString = function () {
  18961. return this.name;
  18962. };
  18963. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18964. set: function (callback) {
  18965. if (this._onDisposeObserver) {
  18966. this.onDisposeObservable.remove(this._onDisposeObserver);
  18967. }
  18968. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18969. },
  18970. enumerable: true,
  18971. configurable: true
  18972. });
  18973. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18974. get: function () {
  18975. return true;
  18976. },
  18977. enumerable: true,
  18978. configurable: true
  18979. });
  18980. BaseTexture.prototype.getScene = function () {
  18981. return this._scene;
  18982. };
  18983. BaseTexture.prototype.getTextureMatrix = function () {
  18984. return null;
  18985. };
  18986. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18987. return null;
  18988. };
  18989. BaseTexture.prototype.getInternalTexture = function () {
  18990. return this._texture;
  18991. };
  18992. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  18993. return !this.isBlocking || this.isReady();
  18994. };
  18995. BaseTexture.prototype.isReady = function () {
  18996. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18997. this.delayLoad();
  18998. return false;
  18999. }
  19000. if (this._texture) {
  19001. return this._texture.isReady;
  19002. }
  19003. return false;
  19004. };
  19005. BaseTexture.prototype.getSize = function () {
  19006. if (this._texture._width) {
  19007. return new BABYLON.Size(this._texture._width, this._texture._height);
  19008. }
  19009. if (this._texture._size) {
  19010. return new BABYLON.Size(this._texture._size, this._texture._size);
  19011. }
  19012. return BABYLON.Size.Zero();
  19013. };
  19014. BaseTexture.prototype.getBaseSize = function () {
  19015. if (!this.isReady() || !this._texture)
  19016. return BABYLON.Size.Zero();
  19017. if (this._texture._size) {
  19018. return new BABYLON.Size(this._texture._size, this._texture._size);
  19019. }
  19020. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  19021. };
  19022. BaseTexture.prototype.scale = function (ratio) {
  19023. };
  19024. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  19025. get: function () {
  19026. return false;
  19027. },
  19028. enumerable: true,
  19029. configurable: true
  19030. });
  19031. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  19032. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19033. for (var index = 0; index < texturesCache.length; index++) {
  19034. var texturesCacheEntry = texturesCache[index];
  19035. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  19036. texturesCache.splice(index, 1);
  19037. return;
  19038. }
  19039. }
  19040. };
  19041. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  19042. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19043. for (var index = 0; index < texturesCache.length; index++) {
  19044. var texturesCacheEntry = texturesCache[index];
  19045. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  19046. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  19047. texturesCacheEntry.references++;
  19048. return texturesCacheEntry;
  19049. }
  19050. }
  19051. }
  19052. return null;
  19053. };
  19054. BaseTexture.prototype.delayLoad = function () {
  19055. };
  19056. BaseTexture.prototype.clone = function () {
  19057. return null;
  19058. };
  19059. BaseTexture.prototype.readPixels = function (faceIndex) {
  19060. if (faceIndex === void 0) { faceIndex = 0; }
  19061. if (!this._texture) {
  19062. return null;
  19063. }
  19064. var size = this.getSize();
  19065. var engine = this.getScene().getEngine();
  19066. if (this._texture.isCube) {
  19067. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  19068. }
  19069. return engine._readTexturePixels(this._texture, size.width, size.height);
  19070. };
  19071. BaseTexture.prototype.releaseInternalTexture = function () {
  19072. if (this._texture) {
  19073. this._scene.getEngine().releaseInternalTexture(this._texture);
  19074. delete this._texture;
  19075. }
  19076. };
  19077. BaseTexture.prototype.dispose = function () {
  19078. // Animations
  19079. this.getScene().stopAnimation(this);
  19080. // Remove from scene
  19081. this._scene._removePendingData(this);
  19082. var index = this._scene.textures.indexOf(this);
  19083. if (index >= 0) {
  19084. this._scene.textures.splice(index, 1);
  19085. }
  19086. if (this._texture === undefined) {
  19087. return;
  19088. }
  19089. // Release
  19090. this.releaseInternalTexture();
  19091. // Callback
  19092. this.onDisposeObservable.notifyObservers(this);
  19093. this.onDisposeObservable.clear();
  19094. };
  19095. BaseTexture.prototype.serialize = function () {
  19096. if (!this.name) {
  19097. return null;
  19098. }
  19099. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19100. // Animations
  19101. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19102. return serializationObject;
  19103. };
  19104. BaseTexture.WhenAllReady = function (textures, onLoad) {
  19105. var numReady = 0;
  19106. var _loop_1 = function () {
  19107. texture = textures[i];
  19108. if (texture.isReady()) {
  19109. if (++numReady === textures.length) {
  19110. onLoad();
  19111. }
  19112. }
  19113. else {
  19114. observable = texture.onLoadObservable;
  19115. var callback_1 = function () {
  19116. observable.removeCallback(callback_1);
  19117. if (++numReady === textures.length) {
  19118. onLoad();
  19119. }
  19120. };
  19121. observable.add(callback_1);
  19122. }
  19123. };
  19124. var texture, observable;
  19125. for (var i = 0; i < textures.length; i++) {
  19126. _loop_1();
  19127. }
  19128. };
  19129. return BaseTexture;
  19130. }());
  19131. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  19132. __decorate([
  19133. BABYLON.serialize()
  19134. ], BaseTexture.prototype, "name", void 0);
  19135. __decorate([
  19136. BABYLON.serialize("hasAlpha")
  19137. ], BaseTexture.prototype, "_hasAlpha", void 0);
  19138. __decorate([
  19139. BABYLON.serialize()
  19140. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  19141. __decorate([
  19142. BABYLON.serialize()
  19143. ], BaseTexture.prototype, "level", void 0);
  19144. __decorate([
  19145. BABYLON.serialize()
  19146. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  19147. __decorate([
  19148. BABYLON.serialize("coordinatesMode")
  19149. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  19150. __decorate([
  19151. BABYLON.serialize()
  19152. ], BaseTexture.prototype, "wrapU", void 0);
  19153. __decorate([
  19154. BABYLON.serialize()
  19155. ], BaseTexture.prototype, "wrapV", void 0);
  19156. __decorate([
  19157. BABYLON.serialize()
  19158. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  19159. __decorate([
  19160. BABYLON.serialize()
  19161. ], BaseTexture.prototype, "isCube", void 0);
  19162. __decorate([
  19163. BABYLON.serialize()
  19164. ], BaseTexture.prototype, "isRenderTarget", void 0);
  19165. BABYLON.BaseTexture = BaseTexture;
  19166. })(BABYLON || (BABYLON = {}));
  19167. //# sourceMappingURL=babylon.baseTexture.js.map
  19168. var BABYLON;
  19169. (function (BABYLON) {
  19170. var Texture = (function (_super) {
  19171. __extends(Texture, _super);
  19172. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19173. if (noMipmap === void 0) { noMipmap = false; }
  19174. if (invertY === void 0) { invertY = true; }
  19175. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19176. if (onLoad === void 0) { onLoad = null; }
  19177. if (onError === void 0) { onError = null; }
  19178. if (buffer === void 0) { buffer = null; }
  19179. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19180. var _this = _super.call(this, scene) || this;
  19181. _this.uOffset = 0;
  19182. _this.vOffset = 0;
  19183. _this.uScale = 1.0;
  19184. _this.vScale = 1.0;
  19185. _this.uAng = 0;
  19186. _this.vAng = 0;
  19187. _this.wAng = 0;
  19188. _this._isBlocking = true;
  19189. _this.name = url;
  19190. _this.url = url;
  19191. _this._noMipmap = noMipmap;
  19192. _this._invertY = invertY;
  19193. _this._samplingMode = samplingMode;
  19194. _this._buffer = buffer;
  19195. _this._deleteBuffer = deleteBuffer;
  19196. _this._format = format;
  19197. scene = _this.getScene();
  19198. var load = function () {
  19199. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  19200. _this.onLoadObservable.notifyObservers(_this);
  19201. }
  19202. if (onLoad) {
  19203. onLoad();
  19204. }
  19205. if (!_this.isBlocking) {
  19206. scene.resetCachedMaterial();
  19207. }
  19208. };
  19209. if (!url) {
  19210. _this._delayedOnLoad = load;
  19211. _this._delayedOnError = onError;
  19212. return _this;
  19213. }
  19214. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19215. if (!_this._texture) {
  19216. if (!scene.useDelayedTextureLoading) {
  19217. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19218. if (deleteBuffer) {
  19219. delete _this._buffer;
  19220. }
  19221. }
  19222. else {
  19223. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19224. _this._delayedOnLoad = load;
  19225. _this._delayedOnError = onError;
  19226. }
  19227. }
  19228. else {
  19229. if (_this._texture.isReady) {
  19230. BABYLON.Tools.SetImmediate(function () { return load(); });
  19231. }
  19232. else {
  19233. _this._texture.onLoadedCallbacks.push(load);
  19234. }
  19235. }
  19236. return _this;
  19237. }
  19238. Object.defineProperty(Texture.prototype, "noMipmap", {
  19239. get: function () {
  19240. return this._noMipmap;
  19241. },
  19242. enumerable: true,
  19243. configurable: true
  19244. });
  19245. Object.defineProperty(Texture.prototype, "isBlocking", {
  19246. get: function () {
  19247. return this._isBlocking;
  19248. },
  19249. set: function (value) {
  19250. this._isBlocking = value;
  19251. },
  19252. enumerable: true,
  19253. configurable: true
  19254. });
  19255. Texture.prototype.updateURL = function (url) {
  19256. this.url = url;
  19257. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19258. this.delayLoad();
  19259. };
  19260. Texture.prototype.delayLoad = function () {
  19261. var _this = this;
  19262. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19263. return;
  19264. }
  19265. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19266. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19267. if (!this._texture) {
  19268. 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);
  19269. if (this._deleteBuffer) {
  19270. delete this._buffer;
  19271. }
  19272. }
  19273. else {
  19274. if (this._texture.isReady) {
  19275. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  19276. }
  19277. else {
  19278. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  19279. }
  19280. }
  19281. };
  19282. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19283. if (!this._texture) {
  19284. return;
  19285. }
  19286. this._samplingMode = samplingMode;
  19287. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19288. };
  19289. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19290. x *= this.uScale;
  19291. y *= this.vScale;
  19292. x -= 0.5 * this.uScale;
  19293. y -= 0.5 * this.vScale;
  19294. z -= 0.5;
  19295. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19296. t.x += 0.5 * this.uScale + this.uOffset;
  19297. t.y += 0.5 * this.vScale + this.vOffset;
  19298. t.z += 0.5;
  19299. };
  19300. Texture.prototype.getTextureMatrix = function () {
  19301. if (this.uOffset === this._cachedUOffset &&
  19302. this.vOffset === this._cachedVOffset &&
  19303. this.uScale === this._cachedUScale &&
  19304. this.vScale === this._cachedVScale &&
  19305. this.uAng === this._cachedUAng &&
  19306. this.vAng === this._cachedVAng &&
  19307. this.wAng === this._cachedWAng) {
  19308. return this._cachedTextureMatrix;
  19309. }
  19310. this._cachedUOffset = this.uOffset;
  19311. this._cachedVOffset = this.vOffset;
  19312. this._cachedUScale = this.uScale;
  19313. this._cachedVScale = this.vScale;
  19314. this._cachedUAng = this.uAng;
  19315. this._cachedVAng = this.vAng;
  19316. this._cachedWAng = this.wAng;
  19317. if (!this._cachedTextureMatrix) {
  19318. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19319. this._rowGenerationMatrix = new BABYLON.Matrix();
  19320. this._t0 = BABYLON.Vector3.Zero();
  19321. this._t1 = BABYLON.Vector3.Zero();
  19322. this._t2 = BABYLON.Vector3.Zero();
  19323. }
  19324. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19325. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19326. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19327. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19328. this._t1.subtractInPlace(this._t0);
  19329. this._t2.subtractInPlace(this._t0);
  19330. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19331. this._cachedTextureMatrix.m[0] = this._t1.x;
  19332. this._cachedTextureMatrix.m[1] = this._t1.y;
  19333. this._cachedTextureMatrix.m[2] = this._t1.z;
  19334. this._cachedTextureMatrix.m[4] = this._t2.x;
  19335. this._cachedTextureMatrix.m[5] = this._t2.y;
  19336. this._cachedTextureMatrix.m[6] = this._t2.z;
  19337. this._cachedTextureMatrix.m[8] = this._t0.x;
  19338. this._cachedTextureMatrix.m[9] = this._t0.y;
  19339. this._cachedTextureMatrix.m[10] = this._t0.z;
  19340. return this._cachedTextureMatrix;
  19341. };
  19342. Texture.prototype.getReflectionTextureMatrix = function () {
  19343. if (this.uOffset === this._cachedUOffset &&
  19344. this.vOffset === this._cachedVOffset &&
  19345. this.uScale === this._cachedUScale &&
  19346. this.vScale === this._cachedVScale &&
  19347. this.coordinatesMode === this._cachedCoordinatesMode) {
  19348. return this._cachedTextureMatrix;
  19349. }
  19350. if (!this._cachedTextureMatrix) {
  19351. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19352. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19353. }
  19354. this._cachedCoordinatesMode = this.coordinatesMode;
  19355. switch (this.coordinatesMode) {
  19356. case Texture.PLANAR_MODE:
  19357. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19358. this._cachedTextureMatrix[0] = this.uScale;
  19359. this._cachedTextureMatrix[5] = this.vScale;
  19360. this._cachedTextureMatrix[12] = this.uOffset;
  19361. this._cachedTextureMatrix[13] = this.vOffset;
  19362. break;
  19363. case Texture.PROJECTION_MODE:
  19364. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19365. this._projectionModeMatrix.m[0] = 0.5;
  19366. this._projectionModeMatrix.m[5] = -0.5;
  19367. this._projectionModeMatrix.m[10] = 0.0;
  19368. this._projectionModeMatrix.m[12] = 0.5;
  19369. this._projectionModeMatrix.m[13] = 0.5;
  19370. this._projectionModeMatrix.m[14] = 1.0;
  19371. this._projectionModeMatrix.m[15] = 1.0;
  19372. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19373. break;
  19374. default:
  19375. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19376. break;
  19377. }
  19378. return this._cachedTextureMatrix;
  19379. };
  19380. Texture.prototype.clone = function () {
  19381. var _this = this;
  19382. return BABYLON.SerializationHelper.Clone(function () {
  19383. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19384. }, this);
  19385. };
  19386. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19387. get: function () {
  19388. if (!this._onLoadObservable) {
  19389. this._onLoadObservable = new BABYLON.Observable();
  19390. }
  19391. return this._onLoadObservable;
  19392. },
  19393. enumerable: true,
  19394. configurable: true
  19395. });
  19396. // Statics
  19397. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19398. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19399. if (onLoad === void 0) { onLoad = null; }
  19400. if (onError === void 0) { onError = null; }
  19401. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19402. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19403. };
  19404. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19405. if (parsedTexture.customType) {
  19406. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19407. // Update Sampling Mode
  19408. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19409. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19410. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19411. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19412. }
  19413. }
  19414. return parsedCustomTexture;
  19415. }
  19416. if (parsedTexture.isCube) {
  19417. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19418. }
  19419. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19420. return null;
  19421. }
  19422. var texture = BABYLON.SerializationHelper.Parse(function () {
  19423. if (parsedTexture.mirrorPlane) {
  19424. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19425. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19426. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19427. return mirrorTexture;
  19428. }
  19429. else if (parsedTexture.isRenderTarget) {
  19430. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19431. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19432. return renderTargetTexture;
  19433. }
  19434. else {
  19435. var texture;
  19436. if (parsedTexture.base64String) {
  19437. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19438. }
  19439. else {
  19440. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19441. }
  19442. return texture;
  19443. }
  19444. }, parsedTexture, scene);
  19445. // Update Sampling Mode
  19446. if (parsedTexture.samplingMode) {
  19447. var sampling = parsedTexture.samplingMode;
  19448. if (texture._samplingMode !== sampling) {
  19449. texture.updateSamplingMode(sampling);
  19450. }
  19451. }
  19452. // Animations
  19453. if (parsedTexture.animations) {
  19454. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19455. var parsedAnimation = parsedTexture.animations[animationIndex];
  19456. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19457. }
  19458. }
  19459. return texture;
  19460. };
  19461. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19462. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19463. if (noMipmap === void 0) { noMipmap = false; }
  19464. if (invertY === void 0) { invertY = true; }
  19465. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19466. if (onLoad === void 0) { onLoad = null; }
  19467. if (onError === void 0) { onError = null; }
  19468. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19469. if (name.substr(0, 5) !== "data:") {
  19470. name = "data:" + name;
  19471. }
  19472. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19473. };
  19474. return Texture;
  19475. }(BABYLON.BaseTexture));
  19476. // Constants
  19477. Texture.NEAREST_SAMPLINGMODE = 1;
  19478. Texture.BILINEAR_SAMPLINGMODE = 2;
  19479. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19480. Texture.EXPLICIT_MODE = 0;
  19481. Texture.SPHERICAL_MODE = 1;
  19482. Texture.PLANAR_MODE = 2;
  19483. Texture.CUBIC_MODE = 3;
  19484. Texture.PROJECTION_MODE = 4;
  19485. Texture.SKYBOX_MODE = 5;
  19486. Texture.INVCUBIC_MODE = 6;
  19487. Texture.EQUIRECTANGULAR_MODE = 7;
  19488. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19489. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19490. Texture.CLAMP_ADDRESSMODE = 0;
  19491. Texture.WRAP_ADDRESSMODE = 1;
  19492. Texture.MIRROR_ADDRESSMODE = 2;
  19493. __decorate([
  19494. BABYLON.serialize()
  19495. ], Texture.prototype, "url", void 0);
  19496. __decorate([
  19497. BABYLON.serialize()
  19498. ], Texture.prototype, "uOffset", void 0);
  19499. __decorate([
  19500. BABYLON.serialize()
  19501. ], Texture.prototype, "vOffset", void 0);
  19502. __decorate([
  19503. BABYLON.serialize()
  19504. ], Texture.prototype, "uScale", void 0);
  19505. __decorate([
  19506. BABYLON.serialize()
  19507. ], Texture.prototype, "vScale", void 0);
  19508. __decorate([
  19509. BABYLON.serialize()
  19510. ], Texture.prototype, "uAng", void 0);
  19511. __decorate([
  19512. BABYLON.serialize()
  19513. ], Texture.prototype, "vAng", void 0);
  19514. __decorate([
  19515. BABYLON.serialize()
  19516. ], Texture.prototype, "wAng", void 0);
  19517. __decorate([
  19518. BABYLON.serialize()
  19519. ], Texture.prototype, "isBlocking", null);
  19520. BABYLON.Texture = Texture;
  19521. })(BABYLON || (BABYLON = {}));
  19522. //# sourceMappingURL=babylon.texture.js.map
  19523. var BABYLON;
  19524. (function (BABYLON) {
  19525. var _InstancesBatch = (function () {
  19526. function _InstancesBatch() {
  19527. this.mustReturn = false;
  19528. this.visibleInstances = new Array();
  19529. this.renderSelf = new Array();
  19530. }
  19531. return _InstancesBatch;
  19532. }());
  19533. BABYLON._InstancesBatch = _InstancesBatch;
  19534. var Mesh = (function (_super) {
  19535. __extends(Mesh, _super);
  19536. /**
  19537. * @constructor
  19538. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19539. * @param {Scene} scene The scene to add this mesh to.
  19540. * @param {Node} parent The parent of this mesh, if it has one
  19541. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19542. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19543. * When false, achieved by calling a clone(), also passing False.
  19544. * This will make creation of children, recursive.
  19545. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19546. */
  19547. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19548. if (parent === void 0) { parent = null; }
  19549. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19550. var _this = _super.call(this, name, scene) || this;
  19551. // Events
  19552. /**
  19553. * An event triggered before rendering the mesh
  19554. * @type {BABYLON.Observable}
  19555. */
  19556. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19557. /**
  19558. * An event triggered after rendering the mesh
  19559. * @type {BABYLON.Observable}
  19560. */
  19561. _this.onAfterRenderObservable = new BABYLON.Observable();
  19562. /**
  19563. * An event triggered before drawing the mesh
  19564. * @type {BABYLON.Observable}
  19565. */
  19566. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19567. // Members
  19568. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19569. _this.instances = new Array();
  19570. _this._LODLevels = new Array();
  19571. _this._visibleInstances = {};
  19572. _this._renderIdForInstances = new Array();
  19573. _this._batchCache = new _InstancesBatch();
  19574. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19575. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19576. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19577. // Will be used to save a source mesh reference, If any
  19578. _this._source = null;
  19579. if (source) {
  19580. // Source mesh
  19581. _this._source = source;
  19582. // Geometry
  19583. if (source._geometry) {
  19584. source._geometry.applyToMesh(_this);
  19585. }
  19586. // Deep copy
  19587. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19588. // Parent
  19589. _this.parent = source.parent;
  19590. // Pivot
  19591. _this.setPivotMatrix(source.getPivotMatrix());
  19592. _this.id = name + "." + source.id;
  19593. // Material
  19594. _this.material = source.material;
  19595. var index;
  19596. if (!doNotCloneChildren) {
  19597. // Children
  19598. for (index = 0; index < scene.meshes.length; index++) {
  19599. var mesh = scene.meshes[index];
  19600. if (mesh.parent === source) {
  19601. // doNotCloneChildren is always going to be False
  19602. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19603. }
  19604. }
  19605. }
  19606. // Physics clone
  19607. var physicsEngine = _this.getScene().getPhysicsEngine();
  19608. if (clonePhysicsImpostor && physicsEngine) {
  19609. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19610. if (impostor) {
  19611. _this.physicsImpostor = impostor.clone(_this);
  19612. }
  19613. }
  19614. // Particles
  19615. for (index = 0; index < scene.particleSystems.length; index++) {
  19616. var system = scene.particleSystems[index];
  19617. if (system.emitter === source) {
  19618. system.clone(system.name, _this);
  19619. }
  19620. }
  19621. _this.computeWorldMatrix(true);
  19622. }
  19623. // Parent
  19624. if (parent !== null) {
  19625. _this.parent = parent;
  19626. }
  19627. return _this;
  19628. }
  19629. Object.defineProperty(Mesh, "FRONTSIDE", {
  19630. /**
  19631. * Mesh side orientation : usually the external or front surface
  19632. */
  19633. get: function () {
  19634. return Mesh._FRONTSIDE;
  19635. },
  19636. enumerable: true,
  19637. configurable: true
  19638. });
  19639. Object.defineProperty(Mesh, "BACKSIDE", {
  19640. /**
  19641. * Mesh side orientation : usually the internal or back surface
  19642. */
  19643. get: function () {
  19644. return Mesh._BACKSIDE;
  19645. },
  19646. enumerable: true,
  19647. configurable: true
  19648. });
  19649. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19650. /**
  19651. * Mesh side orientation : both internal and external or front and back surfaces
  19652. */
  19653. get: function () {
  19654. return Mesh._DOUBLESIDE;
  19655. },
  19656. enumerable: true,
  19657. configurable: true
  19658. });
  19659. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19660. /**
  19661. * Mesh side orientation : by default, `FRONTSIDE`
  19662. */
  19663. get: function () {
  19664. return Mesh._DEFAULTSIDE;
  19665. },
  19666. enumerable: true,
  19667. configurable: true
  19668. });
  19669. Object.defineProperty(Mesh, "NO_CAP", {
  19670. /**
  19671. * Mesh cap setting : no cap
  19672. */
  19673. get: function () {
  19674. return Mesh._NO_CAP;
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. Object.defineProperty(Mesh, "CAP_START", {
  19680. /**
  19681. * Mesh cap setting : one cap at the beginning of the mesh
  19682. */
  19683. get: function () {
  19684. return Mesh._CAP_START;
  19685. },
  19686. enumerable: true,
  19687. configurable: true
  19688. });
  19689. Object.defineProperty(Mesh, "CAP_END", {
  19690. /**
  19691. * Mesh cap setting : one cap at the end of the mesh
  19692. */
  19693. get: function () {
  19694. return Mesh._CAP_END;
  19695. },
  19696. enumerable: true,
  19697. configurable: true
  19698. });
  19699. Object.defineProperty(Mesh, "CAP_ALL", {
  19700. /**
  19701. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19702. */
  19703. get: function () {
  19704. return Mesh._CAP_ALL;
  19705. },
  19706. enumerable: true,
  19707. configurable: true
  19708. });
  19709. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19710. set: function (callback) {
  19711. if (this._onBeforeDrawObserver) {
  19712. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19713. }
  19714. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19715. },
  19716. enumerable: true,
  19717. configurable: true
  19718. });
  19719. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19720. get: function () {
  19721. return this._morphTargetManager;
  19722. },
  19723. set: function (value) {
  19724. if (this._morphTargetManager === value) {
  19725. return;
  19726. }
  19727. this._morphTargetManager = value;
  19728. this._syncGeometryWithMorphTargetManager();
  19729. },
  19730. enumerable: true,
  19731. configurable: true
  19732. });
  19733. Object.defineProperty(Mesh.prototype, "source", {
  19734. get: function () {
  19735. return this._source;
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. // Methods
  19741. /**
  19742. * Returns the string "Mesh".
  19743. */
  19744. Mesh.prototype.getClassName = function () {
  19745. return "Mesh";
  19746. };
  19747. /**
  19748. * Returns a string.
  19749. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19750. */
  19751. Mesh.prototype.toString = function (fullDetails) {
  19752. var ret = _super.prototype.toString.call(this, fullDetails);
  19753. ret += ", n vertices: " + this.getTotalVertices();
  19754. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19755. if (this.animations) {
  19756. for (var i = 0; i < this.animations.length; i++) {
  19757. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19758. }
  19759. }
  19760. if (fullDetails) {
  19761. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19762. }
  19763. return ret;
  19764. };
  19765. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19766. /**
  19767. * True if the mesh has some Levels Of Details (LOD).
  19768. * Returns a boolean.
  19769. */
  19770. get: function () {
  19771. return this._LODLevels.length > 0;
  19772. },
  19773. enumerable: true,
  19774. configurable: true
  19775. });
  19776. Mesh.prototype._sortLODLevels = function () {
  19777. this._LODLevels.sort(function (a, b) {
  19778. if (a.distance < b.distance) {
  19779. return 1;
  19780. }
  19781. if (a.distance > b.distance) {
  19782. return -1;
  19783. }
  19784. return 0;
  19785. });
  19786. };
  19787. /**
  19788. * Add a mesh as LOD level triggered at the given distance.
  19789. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19790. * @param {number} distance The distance from the center of the object to show this level
  19791. * @param {Mesh} mesh The mesh to be added as LOD level
  19792. * @return {Mesh} This mesh (for chaining)
  19793. */
  19794. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19795. if (mesh && mesh._masterMesh) {
  19796. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19797. return this;
  19798. }
  19799. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19800. this._LODLevels.push(level);
  19801. if (mesh) {
  19802. mesh._masterMesh = this;
  19803. }
  19804. this._sortLODLevels();
  19805. return this;
  19806. };
  19807. /**
  19808. * Returns the LOD level mesh at the passed distance or null if not found.
  19809. * It is related to the method `addLODLevel(distance, mesh)`.
  19810. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19811. * Returns an object Mesh or `null`.
  19812. */
  19813. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19814. for (var index = 0; index < this._LODLevels.length; index++) {
  19815. var level = this._LODLevels[index];
  19816. if (level.distance === distance) {
  19817. return level.mesh;
  19818. }
  19819. }
  19820. return null;
  19821. };
  19822. /**
  19823. * Remove a mesh from the LOD array
  19824. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19825. * @param {Mesh} mesh The mesh to be removed.
  19826. * @return {Mesh} This mesh (for chaining)
  19827. */
  19828. Mesh.prototype.removeLODLevel = function (mesh) {
  19829. for (var index = 0; index < this._LODLevels.length; index++) {
  19830. if (this._LODLevels[index].mesh === mesh) {
  19831. this._LODLevels.splice(index, 1);
  19832. if (mesh) {
  19833. mesh._masterMesh = null;
  19834. }
  19835. }
  19836. }
  19837. this._sortLODLevels();
  19838. return this;
  19839. };
  19840. /**
  19841. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19842. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19843. */
  19844. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19845. if (!this._LODLevels || this._LODLevels.length === 0) {
  19846. return this;
  19847. }
  19848. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19849. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19850. if (this.onLODLevelSelection) {
  19851. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19852. }
  19853. return this;
  19854. }
  19855. for (var index = 0; index < this._LODLevels.length; index++) {
  19856. var level = this._LODLevels[index];
  19857. if (level.distance < distanceToCamera) {
  19858. if (level.mesh) {
  19859. level.mesh._preActivate();
  19860. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19861. }
  19862. if (this.onLODLevelSelection) {
  19863. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19864. }
  19865. return level.mesh;
  19866. }
  19867. }
  19868. if (this.onLODLevelSelection) {
  19869. this.onLODLevelSelection(distanceToCamera, this, this);
  19870. }
  19871. return this;
  19872. };
  19873. Object.defineProperty(Mesh.prototype, "geometry", {
  19874. /**
  19875. * Returns the mesh internal Geometry object.
  19876. */
  19877. get: function () {
  19878. return this._geometry;
  19879. },
  19880. enumerable: true,
  19881. configurable: true
  19882. });
  19883. /**
  19884. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19885. */
  19886. Mesh.prototype.getTotalVertices = function () {
  19887. if (!this._geometry) {
  19888. return 0;
  19889. }
  19890. return this._geometry.getTotalVertices();
  19891. };
  19892. /**
  19893. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19894. * 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.
  19895. * You can force the copy with forceCopy === true
  19896. * Returns null if the mesh has no geometry or no vertex buffer.
  19897. * Possible `kind` values :
  19898. * - BABYLON.VertexBuffer.PositionKind
  19899. * - BABYLON.VertexBuffer.UVKind
  19900. * - BABYLON.VertexBuffer.UV2Kind
  19901. * - BABYLON.VertexBuffer.UV3Kind
  19902. * - BABYLON.VertexBuffer.UV4Kind
  19903. * - BABYLON.VertexBuffer.UV5Kind
  19904. * - BABYLON.VertexBuffer.UV6Kind
  19905. * - BABYLON.VertexBuffer.ColorKind
  19906. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19907. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19908. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19909. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19910. */
  19911. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19912. if (!this._geometry) {
  19913. return null;
  19914. }
  19915. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19916. };
  19917. /**
  19918. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19919. * Returns `undefined` if the mesh has no geometry.
  19920. * Possible `kind` values :
  19921. * - BABYLON.VertexBuffer.PositionKind
  19922. * - BABYLON.VertexBuffer.UVKind
  19923. * - BABYLON.VertexBuffer.UV2Kind
  19924. * - BABYLON.VertexBuffer.UV3Kind
  19925. * - BABYLON.VertexBuffer.UV4Kind
  19926. * - BABYLON.VertexBuffer.UV5Kind
  19927. * - BABYLON.VertexBuffer.UV6Kind
  19928. * - BABYLON.VertexBuffer.ColorKind
  19929. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19930. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19931. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19932. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19933. */
  19934. Mesh.prototype.getVertexBuffer = function (kind) {
  19935. if (!this._geometry) {
  19936. return undefined;
  19937. }
  19938. return this._geometry.getVertexBuffer(kind);
  19939. };
  19940. /**
  19941. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19942. * Possible `kind` values :
  19943. * - BABYLON.VertexBuffer.PositionKind
  19944. * - BABYLON.VertexBuffer.UVKind
  19945. * - BABYLON.VertexBuffer.UV2Kind
  19946. * - BABYLON.VertexBuffer.UV3Kind
  19947. * - BABYLON.VertexBuffer.UV4Kind
  19948. * - BABYLON.VertexBuffer.UV5Kind
  19949. * - BABYLON.VertexBuffer.UV6Kind
  19950. * - BABYLON.VertexBuffer.ColorKind
  19951. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19952. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19953. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19954. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19955. */
  19956. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19957. if (!this._geometry) {
  19958. if (this._delayInfo) {
  19959. return this._delayInfo.indexOf(kind) !== -1;
  19960. }
  19961. return false;
  19962. }
  19963. return this._geometry.isVerticesDataPresent(kind);
  19964. };
  19965. /**
  19966. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19967. * Possible `kind` values :
  19968. * - BABYLON.VertexBuffer.PositionKind
  19969. * - BABYLON.VertexBuffer.UVKind
  19970. * - BABYLON.VertexBuffer.UV2Kind
  19971. * - BABYLON.VertexBuffer.UV3Kind
  19972. * - BABYLON.VertexBuffer.UV4Kind
  19973. * - BABYLON.VertexBuffer.UV5Kind
  19974. * - BABYLON.VertexBuffer.UV6Kind
  19975. * - BABYLON.VertexBuffer.ColorKind
  19976. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19977. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19978. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19979. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19980. */
  19981. Mesh.prototype.getVerticesDataKinds = function () {
  19982. if (!this._geometry) {
  19983. var result = [];
  19984. if (this._delayInfo) {
  19985. this._delayInfo.forEach(function (kind, index, array) {
  19986. result.push(kind);
  19987. });
  19988. }
  19989. return result;
  19990. }
  19991. return this._geometry.getVerticesDataKinds();
  19992. };
  19993. /**
  19994. * Returns a positive integer : the total number of indices in this mesh geometry.
  19995. * Returns zero if the mesh has no geometry.
  19996. */
  19997. Mesh.prototype.getTotalIndices = function () {
  19998. if (!this._geometry) {
  19999. return 0;
  20000. }
  20001. return this._geometry.getTotalIndices();
  20002. };
  20003. /**
  20004. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20005. * 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.
  20006. * Returns an empty array if the mesh has no geometry.
  20007. */
  20008. Mesh.prototype.getIndices = function (copyWhenShared) {
  20009. if (!this._geometry) {
  20010. return [];
  20011. }
  20012. return this._geometry.getIndices(copyWhenShared);
  20013. };
  20014. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20015. get: function () {
  20016. return this._masterMesh !== null && this._masterMesh !== undefined;
  20017. },
  20018. enumerable: true,
  20019. configurable: true
  20020. });
  20021. /**
  20022. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20023. */
  20024. Mesh.prototype.isReady = function () {
  20025. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20026. return false;
  20027. }
  20028. return _super.prototype.isReady.call(this);
  20029. };
  20030. /**
  20031. * Boolean : true if the mesh has been disposed.
  20032. */
  20033. Mesh.prototype.isDisposed = function () {
  20034. return this._isDisposed;
  20035. };
  20036. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20037. get: function () {
  20038. return this._sideOrientation;
  20039. },
  20040. /**
  20041. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20042. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20043. */
  20044. set: function (sideO) {
  20045. this._sideOrientation = sideO;
  20046. },
  20047. enumerable: true,
  20048. configurable: true
  20049. });
  20050. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20051. /**
  20052. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20053. * This property is pertinent only for updatable parametric shapes.
  20054. */
  20055. get: function () {
  20056. return this._areNormalsFrozen;
  20057. },
  20058. enumerable: true,
  20059. configurable: true
  20060. });
  20061. /**
  20062. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20063. * It has no effect at all on other shapes.
  20064. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20065. * Returns the Mesh.
  20066. */
  20067. Mesh.prototype.freezeNormals = function () {
  20068. this._areNormalsFrozen = true;
  20069. return this;
  20070. };
  20071. /**
  20072. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20073. * It has no effect at all on other shapes.
  20074. * It reactivates the mesh normals computation if it was previously frozen.
  20075. * Returns the Mesh.
  20076. */
  20077. Mesh.prototype.unfreezeNormals = function () {
  20078. this._areNormalsFrozen = false;
  20079. return this;
  20080. };
  20081. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20082. /**
  20083. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20084. */
  20085. set: function (count) {
  20086. this._overridenInstanceCount = count;
  20087. },
  20088. enumerable: true,
  20089. configurable: true
  20090. });
  20091. // Methods
  20092. Mesh.prototype._preActivate = function () {
  20093. var sceneRenderId = this.getScene().getRenderId();
  20094. if (this._preActivateId === sceneRenderId) {
  20095. return this;
  20096. }
  20097. this._preActivateId = sceneRenderId;
  20098. this._visibleInstances = null;
  20099. return this;
  20100. };
  20101. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20102. if (this._visibleInstances) {
  20103. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20104. }
  20105. return this;
  20106. };
  20107. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20108. if (!this._visibleInstances) {
  20109. this._visibleInstances = {};
  20110. this._visibleInstances.defaultRenderId = renderId;
  20111. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20112. }
  20113. if (!this._visibleInstances[renderId]) {
  20114. this._visibleInstances[renderId] = new Array();
  20115. }
  20116. this._visibleInstances[renderId].push(instance);
  20117. return this;
  20118. };
  20119. /**
  20120. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20121. * This means the mesh underlying bounding box and sphere are recomputed.
  20122. * Returns the Mesh.
  20123. */
  20124. Mesh.prototype.refreshBoundingInfo = function () {
  20125. if (this._boundingInfo.isLocked) {
  20126. return;
  20127. }
  20128. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20129. if (data) {
  20130. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20131. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20132. }
  20133. if (this.subMeshes) {
  20134. for (var index = 0; index < this.subMeshes.length; index++) {
  20135. this.subMeshes[index].refreshBoundingInfo();
  20136. }
  20137. }
  20138. this._updateBoundingInfo();
  20139. return this;
  20140. };
  20141. Mesh.prototype._createGlobalSubMesh = function () {
  20142. var totalVertices = this.getTotalVertices();
  20143. if (!totalVertices || !this.getIndices()) {
  20144. return null;
  20145. }
  20146. this.releaseSubMeshes();
  20147. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20148. };
  20149. Mesh.prototype.subdivide = function (count) {
  20150. if (count < 1) {
  20151. return;
  20152. }
  20153. var totalIndices = this.getTotalIndices();
  20154. var subdivisionSize = (totalIndices / count) | 0;
  20155. var offset = 0;
  20156. // Ensure that subdivisionSize is a multiple of 3
  20157. while (subdivisionSize % 3 !== 0) {
  20158. subdivisionSize++;
  20159. }
  20160. this.releaseSubMeshes();
  20161. for (var index = 0; index < count; index++) {
  20162. if (offset >= totalIndices) {
  20163. break;
  20164. }
  20165. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20166. offset += subdivisionSize;
  20167. }
  20168. this.synchronizeInstances();
  20169. };
  20170. /**
  20171. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20172. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20173. * The `data` are either a numeric array either a Float32Array.
  20174. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20175. * 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).
  20176. * Note that a new underlying VertexBuffer object is created each call.
  20177. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20178. *
  20179. * Possible `kind` values :
  20180. * - BABYLON.VertexBuffer.PositionKind
  20181. * - BABYLON.VertexBuffer.UVKind
  20182. * - BABYLON.VertexBuffer.UV2Kind
  20183. * - BABYLON.VertexBuffer.UV3Kind
  20184. * - BABYLON.VertexBuffer.UV4Kind
  20185. * - BABYLON.VertexBuffer.UV5Kind
  20186. * - BABYLON.VertexBuffer.UV6Kind
  20187. * - BABYLON.VertexBuffer.ColorKind
  20188. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20189. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20190. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20191. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20192. *
  20193. * Returns the Mesh.
  20194. */
  20195. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20196. if (!this._geometry) {
  20197. var vertexData = new BABYLON.VertexData();
  20198. vertexData.set(data, kind);
  20199. var scene = this.getScene();
  20200. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20201. }
  20202. else {
  20203. this._geometry.setVerticesData(kind, data, updatable, stride);
  20204. }
  20205. return this;
  20206. };
  20207. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20208. if (updatable === void 0) { updatable = true; }
  20209. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20210. return;
  20211. }
  20212. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20213. };
  20214. /**
  20215. * Sets the mesh VertexBuffer.
  20216. * Returns the Mesh.
  20217. */
  20218. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20219. if (!this._geometry) {
  20220. var scene = this.getScene();
  20221. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20222. }
  20223. this._geometry.setVerticesBuffer(buffer);
  20224. return this;
  20225. };
  20226. /**
  20227. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20228. * If the mesh has no geometry, it is simply returned as it is.
  20229. * The `data` are either a numeric array either a Float32Array.
  20230. * No new underlying VertexBuffer object is created.
  20231. * 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.
  20232. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20233. *
  20234. * Possible `kind` values :
  20235. * - BABYLON.VertexBuffer.PositionKind
  20236. * - BABYLON.VertexBuffer.UVKind
  20237. * - BABYLON.VertexBuffer.UV2Kind
  20238. * - BABYLON.VertexBuffer.UV3Kind
  20239. * - BABYLON.VertexBuffer.UV4Kind
  20240. * - BABYLON.VertexBuffer.UV5Kind
  20241. * - BABYLON.VertexBuffer.UV6Kind
  20242. * - BABYLON.VertexBuffer.ColorKind
  20243. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20244. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20245. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20246. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20247. *
  20248. * Returns the Mesh.
  20249. */
  20250. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20251. if (!this._geometry) {
  20252. return;
  20253. }
  20254. if (!makeItUnique) {
  20255. this._geometry.updateVerticesData(kind, data, updateExtends);
  20256. }
  20257. else {
  20258. this.makeGeometryUnique();
  20259. this.updateVerticesData(kind, data, updateExtends, false);
  20260. }
  20261. return this;
  20262. };
  20263. /**
  20264. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20265. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20266. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20267. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20268. * Returns the Mesh.
  20269. */
  20270. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20271. if (computeNormals === void 0) { computeNormals = true; }
  20272. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20273. positionFunction(positions);
  20274. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20275. if (computeNormals) {
  20276. var indices = this.getIndices();
  20277. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20278. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20279. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20280. }
  20281. return this;
  20282. };
  20283. /**
  20284. * Creates a un-shared specific occurence of the geometry for the mesh.
  20285. * Returns the Mesh.
  20286. */
  20287. Mesh.prototype.makeGeometryUnique = function () {
  20288. if (!this._geometry) {
  20289. return;
  20290. }
  20291. var oldGeometry = this._geometry;
  20292. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20293. oldGeometry.releaseForMesh(this, true);
  20294. geometry.applyToMesh(this);
  20295. return this;
  20296. };
  20297. /**
  20298. * Sets the mesh indices.
  20299. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20300. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20301. * This method creates a new index buffer each call.
  20302. * Returns the Mesh.
  20303. */
  20304. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20305. if (!this._geometry) {
  20306. var vertexData = new BABYLON.VertexData();
  20307. vertexData.indices = indices;
  20308. var scene = this.getScene();
  20309. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20310. }
  20311. else {
  20312. this._geometry.setIndices(indices, totalVertices);
  20313. }
  20314. return this;
  20315. };
  20316. /**
  20317. * Invert the geometry to move from a right handed system to a left handed one.
  20318. * Returns the Mesh.
  20319. */
  20320. Mesh.prototype.toLeftHanded = function () {
  20321. if (!this._geometry) {
  20322. return;
  20323. }
  20324. this._geometry.toLeftHanded();
  20325. return this;
  20326. };
  20327. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20328. var engine = this.getScene().getEngine();
  20329. // Wireframe
  20330. var indexToBind;
  20331. if (this._unIndexed) {
  20332. indexToBind = null;
  20333. }
  20334. else {
  20335. switch (fillMode) {
  20336. case BABYLON.Material.PointFillMode:
  20337. indexToBind = null;
  20338. break;
  20339. case BABYLON.Material.WireFrameFillMode:
  20340. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20341. break;
  20342. default:
  20343. case BABYLON.Material.TriangleFillMode:
  20344. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20345. break;
  20346. }
  20347. }
  20348. // VBOs
  20349. this._geometry._bind(effect, indexToBind);
  20350. return this;
  20351. };
  20352. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20353. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20354. return this;
  20355. }
  20356. this.onBeforeDrawObservable.notifyObservers(this);
  20357. var engine = this.getScene().getEngine();
  20358. // Draw order
  20359. switch (fillMode) {
  20360. case BABYLON.Material.PointFillMode:
  20361. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20362. break;
  20363. case BABYLON.Material.WireFrameFillMode:
  20364. if (this._unIndexed) {
  20365. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20366. }
  20367. else {
  20368. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20369. }
  20370. break;
  20371. default:
  20372. if (this._unIndexed) {
  20373. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20374. }
  20375. else {
  20376. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20377. }
  20378. }
  20379. return this;
  20380. };
  20381. /**
  20382. * Registers for this mesh a javascript function called just before the rendering process.
  20383. * This function is passed the current mesh.
  20384. * Return the Mesh.
  20385. */
  20386. Mesh.prototype.registerBeforeRender = function (func) {
  20387. this.onBeforeRenderObservable.add(func);
  20388. return this;
  20389. };
  20390. /**
  20391. * Disposes a previously registered javascript function called before the rendering.
  20392. * This function is passed the current mesh.
  20393. * Returns the Mesh.
  20394. */
  20395. Mesh.prototype.unregisterBeforeRender = function (func) {
  20396. this.onBeforeRenderObservable.removeCallback(func);
  20397. return this;
  20398. };
  20399. /**
  20400. * Registers for this mesh a javascript function called just after the rendering is complete.
  20401. * This function is passed the current mesh.
  20402. * Returns the Mesh.
  20403. */
  20404. Mesh.prototype.registerAfterRender = function (func) {
  20405. this.onAfterRenderObservable.add(func);
  20406. return this;
  20407. };
  20408. /**
  20409. * Disposes a previously registered javascript function called after the rendering.
  20410. * This function is passed the current mesh.
  20411. * Return the Mesh.
  20412. */
  20413. Mesh.prototype.unregisterAfterRender = function (func) {
  20414. this.onAfterRenderObservable.removeCallback(func);
  20415. return this;
  20416. };
  20417. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20418. var scene = this.getScene();
  20419. this._batchCache.mustReturn = false;
  20420. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20421. this._batchCache.visibleInstances[subMeshId] = null;
  20422. if (this._visibleInstances) {
  20423. var currentRenderId = scene.getRenderId();
  20424. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20425. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20426. var selfRenderId = this._renderId;
  20427. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20428. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20429. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20430. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20431. }
  20432. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20433. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20434. this._batchCache.mustReturn = true;
  20435. return this._batchCache;
  20436. }
  20437. if (currentRenderId !== selfRenderId) {
  20438. this._batchCache.renderSelf[subMeshId] = false;
  20439. }
  20440. }
  20441. this._renderIdForInstances[subMeshId] = currentRenderId;
  20442. }
  20443. return this._batchCache;
  20444. };
  20445. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20446. var visibleInstances = batch.visibleInstances[subMesh._id];
  20447. var matricesCount = visibleInstances.length + 1;
  20448. var bufferSize = matricesCount * 16 * 4;
  20449. var currentInstancesBufferSize = this._instancesBufferSize;
  20450. var instancesBuffer = this._instancesBuffer;
  20451. while (this._instancesBufferSize < bufferSize) {
  20452. this._instancesBufferSize *= 2;
  20453. }
  20454. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20455. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20456. }
  20457. var offset = 0;
  20458. var instancesCount = 0;
  20459. var world = this.getWorldMatrix();
  20460. if (batch.renderSelf[subMesh._id]) {
  20461. world.copyToArray(this._instancesData, offset);
  20462. offset += 16;
  20463. instancesCount++;
  20464. }
  20465. if (visibleInstances) {
  20466. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20467. var instance = visibleInstances[instanceIndex];
  20468. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20469. offset += 16;
  20470. instancesCount++;
  20471. }
  20472. }
  20473. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20474. if (instancesBuffer) {
  20475. instancesBuffer.dispose();
  20476. }
  20477. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20478. this._instancesBuffer = instancesBuffer;
  20479. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20480. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20481. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20482. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20483. }
  20484. else {
  20485. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20486. }
  20487. this.geometry._bind(effect);
  20488. this._draw(subMesh, fillMode, instancesCount);
  20489. engine.unbindInstanceAttributes();
  20490. return this;
  20491. };
  20492. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20493. var scene = this.getScene();
  20494. var engine = scene.getEngine();
  20495. if (hardwareInstancedRendering) {
  20496. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20497. }
  20498. else {
  20499. if (batch.renderSelf[subMesh._id]) {
  20500. // Draw
  20501. if (onBeforeDraw) {
  20502. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20503. }
  20504. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20505. }
  20506. if (batch.visibleInstances[subMesh._id]) {
  20507. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20508. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20509. // World
  20510. var world = instance.getWorldMatrix();
  20511. if (onBeforeDraw) {
  20512. onBeforeDraw(true, world, effectiveMaterial);
  20513. }
  20514. // Draw
  20515. this._draw(subMesh, fillMode);
  20516. }
  20517. }
  20518. }
  20519. return this;
  20520. };
  20521. /**
  20522. * Triggers the draw call for the mesh.
  20523. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20524. * Returns the Mesh.
  20525. */
  20526. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20527. var scene = this.getScene();
  20528. // Managing instances
  20529. var batch = this._getInstancesRenderList(subMesh._id);
  20530. if (batch.mustReturn) {
  20531. return this;
  20532. }
  20533. // Checking geometry state
  20534. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20535. return this;
  20536. }
  20537. var callbackIndex;
  20538. this.onBeforeRenderObservable.notifyObservers(this);
  20539. var engine = scene.getEngine();
  20540. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20541. // Material
  20542. var effectiveMaterial = subMesh.getMaterial();
  20543. if (!effectiveMaterial) {
  20544. return this;
  20545. }
  20546. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20547. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20548. return this;
  20549. }
  20550. }
  20551. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20552. return this;
  20553. }
  20554. // Alpha mode
  20555. if (enableAlphaMode) {
  20556. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20557. }
  20558. // Outline - step 1
  20559. var savedDepthWrite = engine.getDepthWrite();
  20560. if (this.renderOutline) {
  20561. engine.setDepthWrite(false);
  20562. scene.getOutlineRenderer().render(subMesh, batch);
  20563. engine.setDepthWrite(savedDepthWrite);
  20564. }
  20565. var effect;
  20566. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20567. effect = subMesh.effect;
  20568. }
  20569. else {
  20570. effect = effectiveMaterial.getEffect();
  20571. }
  20572. effectiveMaterial._preBind(effect);
  20573. // Bind
  20574. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20575. this._bind(subMesh, effect, fillMode);
  20576. var world = this.getWorldMatrix();
  20577. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20578. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20579. }
  20580. else {
  20581. effectiveMaterial.bind(world, this);
  20582. }
  20583. // Draw
  20584. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20585. // Unbind
  20586. effectiveMaterial.unbind();
  20587. // Outline - step 2
  20588. if (this.renderOutline && savedDepthWrite) {
  20589. engine.setDepthWrite(true);
  20590. engine.setColorWrite(false);
  20591. scene.getOutlineRenderer().render(subMesh, batch);
  20592. engine.setColorWrite(true);
  20593. }
  20594. // Overlay
  20595. if (this.renderOverlay) {
  20596. var currentMode = engine.getAlphaMode();
  20597. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20598. scene.getOutlineRenderer().render(subMesh, batch, true);
  20599. engine.setAlphaMode(currentMode);
  20600. }
  20601. this.onAfterRenderObservable.notifyObservers(this);
  20602. return this;
  20603. };
  20604. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20605. if (isInstance) {
  20606. effectiveMaterial.bindOnlyWorldMatrix(world);
  20607. }
  20608. return this;
  20609. };
  20610. /**
  20611. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20612. */
  20613. Mesh.prototype.getEmittedParticleSystems = function () {
  20614. var results = new Array();
  20615. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20616. var particleSystem = this.getScene().particleSystems[index];
  20617. if (particleSystem.emitter === this) {
  20618. results.push(particleSystem);
  20619. }
  20620. }
  20621. return results;
  20622. };
  20623. /**
  20624. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20625. */
  20626. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20627. var results = new Array();
  20628. var descendants = this.getDescendants();
  20629. descendants.push(this);
  20630. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20631. var particleSystem = this.getScene().particleSystems[index];
  20632. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20633. results.push(particleSystem);
  20634. }
  20635. }
  20636. return results;
  20637. };
  20638. Mesh.prototype._checkDelayState = function () {
  20639. var scene = this.getScene();
  20640. if (this._geometry) {
  20641. this._geometry.load(scene);
  20642. }
  20643. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20644. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20645. this._queueLoad(this, scene);
  20646. }
  20647. return this;
  20648. };
  20649. Mesh.prototype._queueLoad = function (mesh, scene) {
  20650. var _this = this;
  20651. scene._addPendingData(mesh);
  20652. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20653. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20654. if (data instanceof ArrayBuffer) {
  20655. _this._delayLoadingFunction(data, _this);
  20656. }
  20657. else {
  20658. _this._delayLoadingFunction(JSON.parse(data), _this);
  20659. }
  20660. _this.instances.forEach(function (instance) {
  20661. instance._syncSubMeshes();
  20662. });
  20663. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20664. scene._removePendingData(_this);
  20665. }, function () { }, scene.database, getBinaryData);
  20666. return this;
  20667. };
  20668. /**
  20669. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20670. */
  20671. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20672. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20673. return false;
  20674. }
  20675. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20676. return false;
  20677. }
  20678. this._checkDelayState();
  20679. return true;
  20680. };
  20681. /**
  20682. * Sets the mesh material by the material or multiMaterial `id` property.
  20683. * The material `id` is a string identifying the material or the multiMaterial.
  20684. * This method returns the Mesh.
  20685. */
  20686. Mesh.prototype.setMaterialByID = function (id) {
  20687. var materials = this.getScene().materials;
  20688. var index;
  20689. for (index = materials.length - 1; index > -1; index--) {
  20690. if (materials[index].id === id) {
  20691. this.material = materials[index];
  20692. return this;
  20693. }
  20694. }
  20695. // Multi
  20696. var multiMaterials = this.getScene().multiMaterials;
  20697. for (index = multiMaterials.length - 1; index > -1; index--) {
  20698. if (multiMaterials[index].id === id) {
  20699. this.material = multiMaterials[index];
  20700. return this;
  20701. }
  20702. }
  20703. return this;
  20704. };
  20705. /**
  20706. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20707. */
  20708. Mesh.prototype.getAnimatables = function () {
  20709. var results = [];
  20710. if (this.material) {
  20711. results.push(this.material);
  20712. }
  20713. if (this.skeleton) {
  20714. results.push(this.skeleton);
  20715. }
  20716. return results;
  20717. };
  20718. /**
  20719. * Modifies the mesh geometry according to the passed transformation matrix.
  20720. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20721. * The mesh normals are modified accordingly the same transformation.
  20722. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20723. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20724. * Returns the Mesh.
  20725. */
  20726. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20727. // Position
  20728. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20729. return this;
  20730. }
  20731. var submeshes = this.subMeshes.splice(0);
  20732. this._resetPointsArrayCache();
  20733. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20734. var temp = [];
  20735. var index;
  20736. for (index = 0; index < data.length; index += 3) {
  20737. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20738. }
  20739. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20740. // Normals
  20741. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20742. return this;
  20743. }
  20744. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20745. temp = [];
  20746. for (index = 0; index < data.length; index += 3) {
  20747. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20748. }
  20749. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20750. // flip faces?
  20751. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20752. this.flipFaces();
  20753. }
  20754. // Restore submeshes
  20755. this.releaseSubMeshes();
  20756. this.subMeshes = submeshes;
  20757. return this;
  20758. };
  20759. /**
  20760. * Modifies the mesh geometry according to its own current World Matrix.
  20761. * The mesh World Matrix is then reset.
  20762. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20763. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20764. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20765. * Returns the Mesh.
  20766. */
  20767. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20768. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20769. this.scaling.copyFromFloats(1, 1, 1);
  20770. this.position.copyFromFloats(0, 0, 0);
  20771. this.rotation.copyFromFloats(0, 0, 0);
  20772. //only if quaternion is already set
  20773. if (this.rotationQuaternion) {
  20774. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20775. }
  20776. this._worldMatrix = BABYLON.Matrix.Identity();
  20777. return this;
  20778. };
  20779. Object.defineProperty(Mesh.prototype, "_positions", {
  20780. // Cache
  20781. get: function () {
  20782. if (this._geometry) {
  20783. return this._geometry._positions;
  20784. }
  20785. return null;
  20786. },
  20787. enumerable: true,
  20788. configurable: true
  20789. });
  20790. Mesh.prototype._resetPointsArrayCache = function () {
  20791. if (this._geometry) {
  20792. this._geometry._resetPointsArrayCache();
  20793. }
  20794. return this;
  20795. };
  20796. Mesh.prototype._generatePointsArray = function () {
  20797. if (this._geometry) {
  20798. return this._geometry._generatePointsArray();
  20799. }
  20800. return false;
  20801. };
  20802. /**
  20803. * Returns a new Mesh object generated from the current mesh properties.
  20804. * This method must not get confused with createInstance().
  20805. * The parameter `name` is a string, the name given to the new mesh.
  20806. * The optional parameter `newParent` can be any Node object (default `null`).
  20807. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20808. * 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.
  20809. */
  20810. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20811. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20812. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20813. };
  20814. /**
  20815. * Disposes the mesh.
  20816. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20817. */
  20818. Mesh.prototype.dispose = function (doNotRecurse) {
  20819. var _this = this;
  20820. this.morphTargetManager = undefined;
  20821. if (this._geometry) {
  20822. this._geometry.releaseForMesh(this, true);
  20823. }
  20824. // Sources
  20825. var meshes = this.getScene().meshes;
  20826. meshes.forEach(function (mesh) {
  20827. if (mesh._source && mesh._source === _this) {
  20828. mesh._source = null;
  20829. }
  20830. });
  20831. this._source = null;
  20832. // Instances
  20833. if (this._instancesBuffer) {
  20834. this._instancesBuffer.dispose();
  20835. this._instancesBuffer = null;
  20836. }
  20837. while (this.instances.length) {
  20838. this.instances[0].dispose();
  20839. }
  20840. // Highlight layers.
  20841. var highlightLayers = this.getScene().highlightLayers;
  20842. for (var i = 0; i < highlightLayers.length; i++) {
  20843. var highlightLayer = highlightLayers[i];
  20844. if (highlightLayer) {
  20845. highlightLayer.removeMesh(this);
  20846. highlightLayer.removeExcludedMesh(this);
  20847. }
  20848. }
  20849. _super.prototype.dispose.call(this, doNotRecurse);
  20850. };
  20851. /**
  20852. * Modifies the mesh geometry according to a displacement map.
  20853. * 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.
  20854. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20855. * This method returns nothing.
  20856. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20857. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20858. * 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.
  20859. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20860. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20861. *
  20862. * Returns the Mesh.
  20863. */
  20864. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20865. var _this = this;
  20866. var scene = this.getScene();
  20867. var onload = function (img) {
  20868. // Getting height map data
  20869. var canvas = document.createElement("canvas");
  20870. var context = canvas.getContext("2d");
  20871. var heightMapWidth = img.width;
  20872. var heightMapHeight = img.height;
  20873. canvas.width = heightMapWidth;
  20874. canvas.height = heightMapHeight;
  20875. context.drawImage(img, 0, 0);
  20876. // Create VertexData from map data
  20877. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20878. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20879. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20880. //execute success callback, if set
  20881. if (onSuccess) {
  20882. onSuccess(_this);
  20883. }
  20884. };
  20885. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20886. return this;
  20887. };
  20888. /**
  20889. * Modifies the mesh geometry according to a displacementMap buffer.
  20890. * 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.
  20891. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20892. * This method returns nothing.
  20893. * 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.
  20894. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20895. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20896. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20897. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20898. *
  20899. * Returns the Mesh.
  20900. */
  20901. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20902. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20903. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20904. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20905. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20906. return this;
  20907. }
  20908. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20909. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20910. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20911. var position = BABYLON.Vector3.Zero();
  20912. var normal = BABYLON.Vector3.Zero();
  20913. var uv = BABYLON.Vector2.Zero();
  20914. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20915. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20916. for (var index = 0; index < positions.length; index += 3) {
  20917. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20918. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20919. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20920. // Compute height
  20921. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20922. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20923. var pos = (u + v * heightMapWidth) * 4;
  20924. var r = buffer[pos] / 255.0;
  20925. var g = buffer[pos + 1] / 255.0;
  20926. var b = buffer[pos + 2] / 255.0;
  20927. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20928. normal.normalize();
  20929. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20930. position = position.add(normal);
  20931. position.toArray(positions, index);
  20932. }
  20933. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20934. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20935. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20936. return this;
  20937. };
  20938. /**
  20939. * Modify the mesh to get a flat shading rendering.
  20940. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20941. * This method returns the Mesh.
  20942. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20943. */
  20944. Mesh.prototype.convertToFlatShadedMesh = function () {
  20945. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20946. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20947. var kinds = this.getVerticesDataKinds();
  20948. var vbs = [];
  20949. var data = [];
  20950. var newdata = [];
  20951. var updatableNormals = false;
  20952. var kindIndex;
  20953. var kind;
  20954. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20955. kind = kinds[kindIndex];
  20956. var vertexBuffer = this.getVertexBuffer(kind);
  20957. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20958. updatableNormals = vertexBuffer.isUpdatable();
  20959. kinds.splice(kindIndex, 1);
  20960. kindIndex--;
  20961. continue;
  20962. }
  20963. vbs[kind] = vertexBuffer;
  20964. data[kind] = vbs[kind].getData();
  20965. newdata[kind] = [];
  20966. }
  20967. // Save previous submeshes
  20968. var previousSubmeshes = this.subMeshes.slice(0);
  20969. var indices = this.getIndices();
  20970. var totalIndices = this.getTotalIndices();
  20971. // Generating unique vertices per face
  20972. var index;
  20973. for (index = 0; index < totalIndices; index++) {
  20974. var vertexIndex = indices[index];
  20975. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20976. kind = kinds[kindIndex];
  20977. var stride = vbs[kind].getStrideSize();
  20978. for (var offset = 0; offset < stride; offset++) {
  20979. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20980. }
  20981. }
  20982. }
  20983. // Updating faces & normal
  20984. var normals = [];
  20985. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20986. for (index = 0; index < totalIndices; index += 3) {
  20987. indices[index] = index;
  20988. indices[index + 1] = index + 1;
  20989. indices[index + 2] = index + 2;
  20990. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20991. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20992. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20993. var p1p2 = p1.subtract(p2);
  20994. var p3p2 = p3.subtract(p2);
  20995. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20996. // Store same normals for every vertex
  20997. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20998. normals.push(normal.x);
  20999. normals.push(normal.y);
  21000. normals.push(normal.z);
  21001. }
  21002. }
  21003. this.setIndices(indices);
  21004. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21005. // Updating vertex buffers
  21006. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21007. kind = kinds[kindIndex];
  21008. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21009. }
  21010. // Updating submeshes
  21011. this.releaseSubMeshes();
  21012. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21013. var previousOne = previousSubmeshes[submeshIndex];
  21014. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21015. }
  21016. this.synchronizeInstances();
  21017. return this;
  21018. };
  21019. /**
  21020. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21021. * In other words, more vertices, no more indices and a single bigger VBO.
  21022. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21023. * Returns the Mesh.
  21024. */
  21025. Mesh.prototype.convertToUnIndexedMesh = function () {
  21026. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21027. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21028. var kinds = this.getVerticesDataKinds();
  21029. var vbs = [];
  21030. var data = [];
  21031. var newdata = [];
  21032. var updatableNormals = false;
  21033. var kindIndex;
  21034. var kind;
  21035. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21036. kind = kinds[kindIndex];
  21037. var vertexBuffer = this.getVertexBuffer(kind);
  21038. vbs[kind] = vertexBuffer;
  21039. data[kind] = vbs[kind].getData();
  21040. newdata[kind] = [];
  21041. }
  21042. // Save previous submeshes
  21043. var previousSubmeshes = this.subMeshes.slice(0);
  21044. var indices = this.getIndices();
  21045. var totalIndices = this.getTotalIndices();
  21046. // Generating unique vertices per face
  21047. var index;
  21048. for (index = 0; index < totalIndices; index++) {
  21049. var vertexIndex = indices[index];
  21050. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21051. kind = kinds[kindIndex];
  21052. var stride = vbs[kind].getStrideSize();
  21053. for (var offset = 0; offset < stride; offset++) {
  21054. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21055. }
  21056. }
  21057. }
  21058. // Updating indices
  21059. for (index = 0; index < totalIndices; index += 3) {
  21060. indices[index] = index;
  21061. indices[index + 1] = index + 1;
  21062. indices[index + 2] = index + 2;
  21063. }
  21064. this.setIndices(indices);
  21065. // Updating vertex buffers
  21066. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21067. kind = kinds[kindIndex];
  21068. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21069. }
  21070. // Updating submeshes
  21071. this.releaseSubMeshes();
  21072. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21073. var previousOne = previousSubmeshes[submeshIndex];
  21074. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21075. }
  21076. this._unIndexed = true;
  21077. this.synchronizeInstances();
  21078. return this;
  21079. };
  21080. /**
  21081. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21082. * This method returns the Mesh.
  21083. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21084. */
  21085. Mesh.prototype.flipFaces = function (flipNormals) {
  21086. if (flipNormals === void 0) { flipNormals = false; }
  21087. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21088. var i;
  21089. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21090. for (i = 0; i < vertex_data.normals.length; i++) {
  21091. vertex_data.normals[i] *= -1;
  21092. }
  21093. }
  21094. var temp;
  21095. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21096. // reassign indices
  21097. temp = vertex_data.indices[i + 1];
  21098. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21099. vertex_data.indices[i + 2] = temp;
  21100. }
  21101. vertex_data.applyToMesh(this);
  21102. return this;
  21103. };
  21104. // Instances
  21105. /**
  21106. * Creates a new InstancedMesh object from the mesh model.
  21107. * An instance shares the same properties and the same material than its model.
  21108. * Only these properties of each instance can then be set individually :
  21109. * - position
  21110. * - rotation
  21111. * - rotationQuaternion
  21112. * - setPivotMatrix
  21113. * - scaling
  21114. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21115. * Warning : this method is not supported for Line mesh and LineSystem
  21116. */
  21117. Mesh.prototype.createInstance = function (name) {
  21118. return new BABYLON.InstancedMesh(name, this);
  21119. };
  21120. /**
  21121. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21122. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21123. * This method returns the Mesh.
  21124. */
  21125. Mesh.prototype.synchronizeInstances = function () {
  21126. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21127. var instance = this.instances[instanceIndex];
  21128. instance._syncSubMeshes();
  21129. }
  21130. return this;
  21131. };
  21132. /**
  21133. * Simplify the mesh according to the given array of settings.
  21134. * Function will return immediately and will simplify async. It returns the Mesh.
  21135. * @param settings a collection of simplification settings.
  21136. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21137. * @param type the type of simplification to run.
  21138. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21139. */
  21140. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21141. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21142. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21143. this.getScene().simplificationQueue.addTask({
  21144. settings: settings,
  21145. parallelProcessing: parallelProcessing,
  21146. mesh: this,
  21147. simplificationType: simplificationType,
  21148. successCallback: successCallback
  21149. });
  21150. return this;
  21151. };
  21152. /**
  21153. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21154. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21155. * This should be used together with the simplification to avoid disappearing triangles.
  21156. * Returns the Mesh.
  21157. * @param successCallback an optional success callback to be called after the optimization finished.
  21158. */
  21159. Mesh.prototype.optimizeIndices = function (successCallback) {
  21160. var _this = this;
  21161. var indices = this.getIndices();
  21162. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21163. var vectorPositions = [];
  21164. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21165. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21166. }
  21167. var dupes = [];
  21168. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21169. var realPos = vectorPositions.length - 1 - iteration;
  21170. var testedPosition = vectorPositions[realPos];
  21171. for (var j = 0; j < realPos; ++j) {
  21172. var againstPosition = vectorPositions[j];
  21173. if (testedPosition.equals(againstPosition)) {
  21174. dupes[realPos] = j;
  21175. break;
  21176. }
  21177. }
  21178. }, function () {
  21179. for (var i = 0; i < indices.length; ++i) {
  21180. indices[i] = dupes[indices[i]] || indices[i];
  21181. }
  21182. //indices are now reordered
  21183. var originalSubMeshes = _this.subMeshes.slice(0);
  21184. _this.setIndices(indices);
  21185. _this.subMeshes = originalSubMeshes;
  21186. if (successCallback) {
  21187. successCallback(_this);
  21188. }
  21189. });
  21190. return this;
  21191. };
  21192. Mesh.prototype.serialize = function (serializationObject) {
  21193. serializationObject.name = this.name;
  21194. serializationObject.id = this.id;
  21195. serializationObject.type = this.getClassName();
  21196. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21197. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21198. }
  21199. serializationObject.position = this.position.asArray();
  21200. if (this.rotationQuaternion) {
  21201. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21202. }
  21203. else if (this.rotation) {
  21204. serializationObject.rotation = this.rotation.asArray();
  21205. }
  21206. serializationObject.scaling = this.scaling.asArray();
  21207. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21208. serializationObject.isEnabled = this.isEnabled();
  21209. serializationObject.isVisible = this.isVisible;
  21210. serializationObject.infiniteDistance = this.infiniteDistance;
  21211. serializationObject.pickable = this.isPickable;
  21212. serializationObject.receiveShadows = this.receiveShadows;
  21213. serializationObject.billboardMode = this.billboardMode;
  21214. serializationObject.visibility = this.visibility;
  21215. serializationObject.checkCollisions = this.checkCollisions;
  21216. serializationObject.isBlocker = this.isBlocker;
  21217. // Parent
  21218. if (this.parent) {
  21219. serializationObject.parentId = this.parent.id;
  21220. }
  21221. // Geometry
  21222. var geometry = this._geometry;
  21223. if (geometry) {
  21224. var geometryId = geometry.id;
  21225. serializationObject.geometryId = geometryId;
  21226. // SubMeshes
  21227. serializationObject.subMeshes = [];
  21228. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21229. var subMesh = this.subMeshes[subIndex];
  21230. serializationObject.subMeshes.push({
  21231. materialIndex: subMesh.materialIndex,
  21232. verticesStart: subMesh.verticesStart,
  21233. verticesCount: subMesh.verticesCount,
  21234. indexStart: subMesh.indexStart,
  21235. indexCount: subMesh.indexCount
  21236. });
  21237. }
  21238. }
  21239. // Material
  21240. if (this.material) {
  21241. serializationObject.materialId = this.material.id;
  21242. }
  21243. else {
  21244. this.material = null;
  21245. }
  21246. // Morph targets
  21247. if (this.morphTargetManager) {
  21248. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21249. }
  21250. // Skeleton
  21251. if (this.skeleton) {
  21252. serializationObject.skeletonId = this.skeleton.id;
  21253. }
  21254. // Physics
  21255. //TODO implement correct serialization for physics impostors.
  21256. if (this.getPhysicsImpostor()) {
  21257. var impostor = this.getPhysicsImpostor();
  21258. serializationObject.physicsMass = impostor.getParam("mass");
  21259. serializationObject.physicsFriction = impostor.getParam("friction");
  21260. serializationObject.physicsRestitution = impostor.getParam("mass");
  21261. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21262. }
  21263. // Metadata
  21264. if (this.metadata) {
  21265. serializationObject.metadata = this.metadata;
  21266. }
  21267. // Instances
  21268. serializationObject.instances = [];
  21269. for (var index = 0; index < this.instances.length; index++) {
  21270. var instance = this.instances[index];
  21271. var serializationInstance = {
  21272. name: instance.name,
  21273. position: instance.position.asArray(),
  21274. scaling: instance.scaling.asArray()
  21275. };
  21276. if (instance.rotationQuaternion) {
  21277. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21278. }
  21279. else if (instance.rotation) {
  21280. serializationInstance.rotation = instance.rotation.asArray();
  21281. }
  21282. serializationObject.instances.push(serializationInstance);
  21283. // Animations
  21284. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21285. serializationInstance.ranges = instance.serializeAnimationRanges();
  21286. }
  21287. //
  21288. // Animations
  21289. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21290. serializationObject.ranges = this.serializeAnimationRanges();
  21291. // Layer mask
  21292. serializationObject.layerMask = this.layerMask;
  21293. // Alpha
  21294. serializationObject.alphaIndex = this.alphaIndex;
  21295. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21296. // Overlay
  21297. serializationObject.overlayAlpha = this.overlayAlpha;
  21298. serializationObject.overlayColor = this.overlayColor.asArray();
  21299. serializationObject.renderOverlay = this.renderOverlay;
  21300. // Fog
  21301. serializationObject.applyFog = this.applyFog;
  21302. // Action Manager
  21303. if (this.actionManager) {
  21304. serializationObject.actions = this.actionManager.serialize(this.name);
  21305. }
  21306. };
  21307. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21308. if (!this.geometry) {
  21309. return;
  21310. }
  21311. this._markSubMeshesAsAttributesDirty();
  21312. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21313. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21314. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21315. this.morphTargetManager = undefined;
  21316. return;
  21317. }
  21318. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21319. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21320. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21321. if (morphTarget.hasNormals) {
  21322. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21323. }
  21324. if (morphTarget.hasTangents) {
  21325. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21326. }
  21327. }
  21328. }
  21329. else {
  21330. var index = 0;
  21331. // Positions
  21332. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21333. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21334. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21335. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21336. }
  21337. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21338. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21339. }
  21340. index++;
  21341. }
  21342. }
  21343. };
  21344. // Statics
  21345. /**
  21346. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21347. * The parameter `parsedMesh` is the mesh to be copied.
  21348. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21349. */
  21350. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21351. var mesh;
  21352. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21353. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21354. }
  21355. else {
  21356. mesh = new Mesh(parsedMesh.name, scene);
  21357. }
  21358. mesh.id = parsedMesh.id;
  21359. if (BABYLON.Tags) {
  21360. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21361. }
  21362. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21363. if (parsedMesh.metadata !== undefined) {
  21364. mesh.metadata = parsedMesh.metadata;
  21365. }
  21366. if (parsedMesh.rotationQuaternion) {
  21367. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21368. }
  21369. else if (parsedMesh.rotation) {
  21370. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21371. }
  21372. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21373. if (parsedMesh.localMatrix) {
  21374. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21375. }
  21376. else if (parsedMesh.pivotMatrix) {
  21377. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21378. }
  21379. mesh.setEnabled(parsedMesh.isEnabled);
  21380. mesh.isVisible = parsedMesh.isVisible;
  21381. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21382. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21383. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21384. if (parsedMesh.applyFog !== undefined) {
  21385. mesh.applyFog = parsedMesh.applyFog;
  21386. }
  21387. if (parsedMesh.pickable !== undefined) {
  21388. mesh.isPickable = parsedMesh.pickable;
  21389. }
  21390. if (parsedMesh.alphaIndex !== undefined) {
  21391. mesh.alphaIndex = parsedMesh.alphaIndex;
  21392. }
  21393. mesh.receiveShadows = parsedMesh.receiveShadows;
  21394. mesh.billboardMode = parsedMesh.billboardMode;
  21395. if (parsedMesh.visibility !== undefined) {
  21396. mesh.visibility = parsedMesh.visibility;
  21397. }
  21398. mesh.checkCollisions = parsedMesh.checkCollisions;
  21399. if (parsedMesh.isBlocker !== undefined) {
  21400. mesh.isBlocker = parsedMesh.isBlocker;
  21401. }
  21402. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21403. // freezeWorldMatrix
  21404. if (parsedMesh.freezeWorldMatrix) {
  21405. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21406. }
  21407. // Parent
  21408. if (parsedMesh.parentId) {
  21409. mesh._waitingParentId = parsedMesh.parentId;
  21410. }
  21411. // Actions
  21412. if (parsedMesh.actions !== undefined) {
  21413. mesh._waitingActions = parsedMesh.actions;
  21414. }
  21415. // Overlay
  21416. if (parsedMesh.overlayAlpha !== undefined) {
  21417. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21418. }
  21419. if (parsedMesh.overlayColor !== undefined) {
  21420. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21421. }
  21422. if (parsedMesh.renderOverlay !== undefined) {
  21423. mesh.renderOverlay = parsedMesh.renderOverlay;
  21424. }
  21425. // Geometry
  21426. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21427. if (parsedMesh.delayLoadingFile) {
  21428. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21429. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21430. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21431. if (parsedMesh._binaryInfo) {
  21432. mesh._binaryInfo = parsedMesh._binaryInfo;
  21433. }
  21434. mesh._delayInfo = [];
  21435. if (parsedMesh.hasUVs) {
  21436. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21437. }
  21438. if (parsedMesh.hasUVs2) {
  21439. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21440. }
  21441. if (parsedMesh.hasUVs3) {
  21442. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21443. }
  21444. if (parsedMesh.hasUVs4) {
  21445. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21446. }
  21447. if (parsedMesh.hasUVs5) {
  21448. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21449. }
  21450. if (parsedMesh.hasUVs6) {
  21451. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21452. }
  21453. if (parsedMesh.hasColors) {
  21454. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21455. }
  21456. if (parsedMesh.hasMatricesIndices) {
  21457. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21458. }
  21459. if (parsedMesh.hasMatricesWeights) {
  21460. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21461. }
  21462. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21463. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21464. mesh._checkDelayState();
  21465. }
  21466. }
  21467. else {
  21468. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21469. }
  21470. // Material
  21471. if (parsedMesh.materialId) {
  21472. mesh.setMaterialByID(parsedMesh.materialId);
  21473. }
  21474. else {
  21475. mesh.material = null;
  21476. }
  21477. // Morph targets
  21478. if (parsedMesh.morphTargetManagerId > -1) {
  21479. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21480. }
  21481. // Skeleton
  21482. if (parsedMesh.skeletonId > -1) {
  21483. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21484. if (parsedMesh.numBoneInfluencers) {
  21485. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21486. }
  21487. }
  21488. // Animations
  21489. if (parsedMesh.animations) {
  21490. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21491. var parsedAnimation = parsedMesh.animations[animationIndex];
  21492. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21493. }
  21494. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21495. }
  21496. if (parsedMesh.autoAnimate) {
  21497. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21498. }
  21499. // Layer Mask
  21500. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21501. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21502. }
  21503. else {
  21504. mesh.layerMask = 0x0FFFFFFF;
  21505. }
  21506. // Physics
  21507. if (parsedMesh.physicsImpostor) {
  21508. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21509. mass: parsedMesh.physicsMass,
  21510. friction: parsedMesh.physicsFriction,
  21511. restitution: parsedMesh.physicsRestitution
  21512. }, scene);
  21513. }
  21514. // Instances
  21515. if (parsedMesh.instances) {
  21516. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21517. var parsedInstance = parsedMesh.instances[index];
  21518. var instance = mesh.createInstance(parsedInstance.name);
  21519. if (BABYLON.Tags) {
  21520. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21521. }
  21522. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21523. if (parsedInstance.parentId) {
  21524. instance._waitingParentId = parsedInstance.parentId;
  21525. }
  21526. if (parsedInstance.rotationQuaternion) {
  21527. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21528. }
  21529. else if (parsedInstance.rotation) {
  21530. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21531. }
  21532. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21533. instance.checkCollisions = mesh.checkCollisions;
  21534. if (parsedMesh.animations) {
  21535. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21536. parsedAnimation = parsedMesh.animations[animationIndex];
  21537. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21538. }
  21539. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21540. }
  21541. }
  21542. }
  21543. return mesh;
  21544. };
  21545. /**
  21546. * Creates a ribbon mesh.
  21547. * Please consider using the same method from the MeshBuilder class instead.
  21548. * 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.
  21549. *
  21550. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21551. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21552. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21553. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21554. * 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.
  21555. * 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.
  21556. * 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
  21557. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21558. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21559. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21560. */
  21561. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21562. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21563. pathArray: pathArray,
  21564. closeArray: closeArray,
  21565. closePath: closePath,
  21566. offset: offset,
  21567. updatable: updatable,
  21568. sideOrientation: sideOrientation,
  21569. instance: instance
  21570. }, scene);
  21571. };
  21572. /**
  21573. * Creates a plane polygonal mesh. By default, this is a disc.
  21574. * Please consider using the same method from the MeshBuilder class instead.
  21575. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21576. * 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.
  21577. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21578. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21580. */
  21581. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21582. var options = {
  21583. radius: radius,
  21584. tessellation: tessellation,
  21585. sideOrientation: sideOrientation,
  21586. updatable: updatable
  21587. };
  21588. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21589. };
  21590. /**
  21591. * Creates a box mesh.
  21592. * Please consider using the same method from the MeshBuilder class instead.
  21593. * The parameter `size` sets the size (float) of each box side (default 1).
  21594. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21595. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21596. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21597. */
  21598. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21599. var options = {
  21600. size: size,
  21601. sideOrientation: sideOrientation,
  21602. updatable: updatable
  21603. };
  21604. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21605. };
  21606. /**
  21607. * Creates a sphere mesh.
  21608. * Please consider using the same method from the MeshBuilder class instead.
  21609. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21610. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21611. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21612. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21613. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21614. */
  21615. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21616. var options = {
  21617. segments: segments,
  21618. diameterX: diameter,
  21619. diameterY: diameter,
  21620. diameterZ: diameter,
  21621. sideOrientation: sideOrientation,
  21622. updatable: updatable
  21623. };
  21624. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21625. };
  21626. /**
  21627. * Creates a cylinder or a cone mesh.
  21628. * Please consider using the same method from the MeshBuilder class instead.
  21629. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21630. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21631. * 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.
  21632. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21633. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21634. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21635. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21636. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21637. */
  21638. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21639. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21640. if (scene !== undefined) {
  21641. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21642. updatable = scene;
  21643. }
  21644. scene = subdivisions;
  21645. subdivisions = 1;
  21646. }
  21647. var options = {
  21648. height: height,
  21649. diameterTop: diameterTop,
  21650. diameterBottom: diameterBottom,
  21651. tessellation: tessellation,
  21652. subdivisions: subdivisions,
  21653. sideOrientation: sideOrientation,
  21654. updatable: updatable
  21655. };
  21656. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21657. };
  21658. // Torus (Code from SharpDX.org)
  21659. /**
  21660. * Creates a torus mesh.
  21661. * Please consider using the same method from the MeshBuilder class instead.
  21662. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21663. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21664. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21665. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21666. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21667. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21668. */
  21669. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21670. var options = {
  21671. diameter: diameter,
  21672. thickness: thickness,
  21673. tessellation: tessellation,
  21674. sideOrientation: sideOrientation,
  21675. updatable: updatable
  21676. };
  21677. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21678. };
  21679. /**
  21680. * Creates a torus knot mesh.
  21681. * Please consider using the same method from the MeshBuilder class instead.
  21682. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21683. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21684. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21685. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21686. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21687. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21688. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21689. */
  21690. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21691. var options = {
  21692. radius: radius,
  21693. tube: tube,
  21694. radialSegments: radialSegments,
  21695. tubularSegments: tubularSegments,
  21696. p: p,
  21697. q: q,
  21698. sideOrientation: sideOrientation,
  21699. updatable: updatable
  21700. };
  21701. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21702. };
  21703. /**
  21704. * Creates a line mesh.
  21705. * Please consider using the same method from the MeshBuilder class instead.
  21706. * 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.
  21707. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21708. * The parameter `points` is an array successive Vector3.
  21709. * 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
  21710. * When updating an instance, remember that only point positions can change, not the number of points.
  21711. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21712. */
  21713. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21714. var options = {
  21715. points: points,
  21716. updatable: updatable,
  21717. instance: instance
  21718. };
  21719. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21720. };
  21721. /**
  21722. * Creates a dashed line mesh.
  21723. * Please consider using the same method from the MeshBuilder class instead.
  21724. * 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.
  21725. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21726. * The parameter `points` is an array successive Vector3.
  21727. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21728. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21729. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21730. * 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
  21731. * When updating an instance, remember that only point positions can change, not the number of points.
  21732. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21733. */
  21734. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21735. var options = {
  21736. points: points,
  21737. dashSize: dashSize,
  21738. gapSize: gapSize,
  21739. dashNb: dashNb,
  21740. updatable: updatable,
  21741. instance: instance
  21742. };
  21743. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21744. };
  21745. /**
  21746. * Creates a polygon mesh.
  21747. * Please consider using the same method from the MeshBuilder class instead.
  21748. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21749. * 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.
  21750. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21752. * Remember you can only change the shape positions, not their number when updating a polygon.
  21753. */
  21754. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21755. var options = {
  21756. shape: shape,
  21757. holes: holes,
  21758. updatable: updatable,
  21759. sideOrientation: sideOrientation
  21760. };
  21761. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21762. };
  21763. /**
  21764. * Creates an extruded polygon mesh, with depth in the Y direction.
  21765. * Please consider using the same method from the MeshBuilder class instead.
  21766. */
  21767. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21768. var options = {
  21769. shape: shape,
  21770. holes: holes,
  21771. depth: depth,
  21772. updatable: updatable,
  21773. sideOrientation: sideOrientation
  21774. };
  21775. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21776. };
  21777. /**
  21778. * Creates an extruded shape mesh.
  21779. * 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.
  21780. * Please consider using the same method from the MeshBuilder class instead.
  21781. *
  21782. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21783. * 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
  21784. * extruded along the Z axis.
  21785. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21786. * 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.
  21787. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21788. * 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
  21789. * 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
  21790. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21791. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21792. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21794. */
  21795. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21796. var options = {
  21797. shape: shape,
  21798. path: path,
  21799. scale: scale,
  21800. rotation: rotation,
  21801. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21802. sideOrientation: sideOrientation,
  21803. instance: instance,
  21804. updatable: updatable
  21805. };
  21806. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21807. };
  21808. /**
  21809. * Creates an custom extruded shape mesh.
  21810. * 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.
  21811. * Please consider using the same method from the MeshBuilder class instead.
  21812. *
  21813. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21814. * 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
  21815. * extruded along the Z axis.
  21816. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21817. * 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
  21818. * and the distance of this point from the begining of the path :
  21819. * ```javascript
  21820. * var rotationFunction = function(i, distance) {
  21821. * // do things
  21822. * return rotationValue; }
  21823. * ```
  21824. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21825. * 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
  21826. * and the distance of this point from the begining of the path :
  21827. * ```javascript
  21828. * var scaleFunction = function(i, distance) {
  21829. * // do things
  21830. * return scaleValue;}
  21831. * ```
  21832. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21833. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21834. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21835. * 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
  21836. * 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
  21837. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21838. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21839. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21840. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21841. */
  21842. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21843. var options = {
  21844. shape: shape,
  21845. path: path,
  21846. scaleFunction: scaleFunction,
  21847. rotationFunction: rotationFunction,
  21848. ribbonCloseArray: ribbonCloseArray,
  21849. ribbonClosePath: ribbonClosePath,
  21850. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21851. sideOrientation: sideOrientation,
  21852. instance: instance,
  21853. updatable: updatable
  21854. };
  21855. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21856. };
  21857. /**
  21858. * Creates lathe mesh.
  21859. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21860. * Please consider using the same method from the MeshBuilder class instead.
  21861. * 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
  21862. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21863. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21864. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21865. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21866. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21868. */
  21869. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21870. var options = {
  21871. shape: shape,
  21872. radius: radius,
  21873. tessellation: tessellation,
  21874. sideOrientation: sideOrientation,
  21875. updatable: updatable
  21876. };
  21877. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21878. };
  21879. /**
  21880. * Creates a plane mesh.
  21881. * Please consider using the same method from the MeshBuilder class instead.
  21882. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21883. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21884. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21885. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21886. */
  21887. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21888. var options = {
  21889. size: size,
  21890. width: size,
  21891. height: size,
  21892. sideOrientation: sideOrientation,
  21893. updatable: updatable
  21894. };
  21895. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21896. };
  21897. /**
  21898. * Creates a ground mesh.
  21899. * Please consider using the same method from the MeshBuilder class instead.
  21900. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21901. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21903. */
  21904. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21905. var options = {
  21906. width: width,
  21907. height: height,
  21908. subdivisions: subdivisions,
  21909. updatable: updatable
  21910. };
  21911. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21912. };
  21913. /**
  21914. * Creates a tiled ground mesh.
  21915. * Please consider using the same method from the MeshBuilder class instead.
  21916. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21917. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21918. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21919. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21920. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21921. * numbers of subdivisions on the ground width and height of each tile.
  21922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21923. */
  21924. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21925. var options = {
  21926. xmin: xmin,
  21927. zmin: zmin,
  21928. xmax: xmax,
  21929. zmax: zmax,
  21930. subdivisions: subdivisions,
  21931. precision: precision,
  21932. updatable: updatable
  21933. };
  21934. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21935. };
  21936. /**
  21937. * Creates a ground mesh from a height map.
  21938. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21939. * Please consider using the same method from the MeshBuilder class instead.
  21940. * The parameter `url` sets the URL of the height map image resource.
  21941. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21942. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21943. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21944. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21945. * 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).
  21946. * This function is passed the newly built mesh :
  21947. * ```javascript
  21948. * function(mesh) { // do things
  21949. * return; }
  21950. * ```
  21951. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21952. */
  21953. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21954. var options = {
  21955. width: width,
  21956. height: height,
  21957. subdivisions: subdivisions,
  21958. minHeight: minHeight,
  21959. maxHeight: maxHeight,
  21960. updatable: updatable,
  21961. onReady: onReady
  21962. };
  21963. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21964. };
  21965. /**
  21966. * Creates a tube mesh.
  21967. * 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.
  21968. * Please consider using the same method from the MeshBuilder class instead.
  21969. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21970. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21971. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21972. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21973. * 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.
  21974. * It must return a radius value (positive float) :
  21975. * ```javascript
  21976. * var radiusFunction = function(i, distance) {
  21977. * // do things
  21978. * return radius; }
  21979. * ```
  21980. * 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
  21981. * 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
  21982. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21983. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21984. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21985. */
  21986. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21987. var options = {
  21988. path: path,
  21989. radius: radius,
  21990. tessellation: tessellation,
  21991. radiusFunction: radiusFunction,
  21992. arc: 1,
  21993. cap: cap,
  21994. updatable: updatable,
  21995. sideOrientation: sideOrientation,
  21996. instance: instance
  21997. };
  21998. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21999. };
  22000. /**
  22001. * Creates a polyhedron mesh.
  22002. * Please consider using the same method from the MeshBuilder class instead.
  22003. * 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
  22004. * to choose the wanted type.
  22005. * The parameter `size` (positive float, default 1) sets the polygon size.
  22006. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22007. * 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`.
  22008. * 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
  22009. * 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)`).
  22010. * 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
  22011. * 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.
  22012. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22013. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22014. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22015. */
  22016. Mesh.CreatePolyhedron = function (name, options, scene) {
  22017. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22018. };
  22019. /**
  22020. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22021. * Please consider using the same method from the MeshBuilder class instead.
  22022. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22023. * 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`).
  22024. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22025. * 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.
  22026. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22027. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22028. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22029. */
  22030. Mesh.CreateIcoSphere = function (name, options, scene) {
  22031. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22032. };
  22033. /**
  22034. * Creates a decal mesh.
  22035. * Please consider using the same method from the MeshBuilder class instead.
  22036. * 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.
  22037. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22038. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22039. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22040. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22041. */
  22042. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22043. var options = {
  22044. position: position,
  22045. normal: normal,
  22046. size: size,
  22047. angle: angle
  22048. };
  22049. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22050. };
  22051. // Skeletons
  22052. /**
  22053. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22054. */
  22055. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22056. var source;
  22057. if (!this._sourcePositions) {
  22058. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22059. this._sourcePositions = new Float32Array(source);
  22060. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22061. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22062. }
  22063. }
  22064. return this._sourcePositions;
  22065. };
  22066. /**
  22067. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22068. */
  22069. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22070. var source;
  22071. if (!this._sourceNormals) {
  22072. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22073. this._sourceNormals = new Float32Array(source);
  22074. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22075. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22076. }
  22077. }
  22078. return this._sourceNormals;
  22079. };
  22080. /**
  22081. * Updates the vertex buffer by applying transformation from the bones.
  22082. * Returns the Mesh.
  22083. *
  22084. * @param {skeleton} skeleton to apply
  22085. */
  22086. Mesh.prototype.applySkeleton = function (skeleton) {
  22087. if (!this.geometry) {
  22088. return this;
  22089. }
  22090. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22091. return this;
  22092. }
  22093. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22094. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22095. return this;
  22096. }
  22097. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22098. return this;
  22099. }
  22100. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22101. return this;
  22102. }
  22103. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22104. return this;
  22105. }
  22106. if (!this._sourcePositions) {
  22107. var submeshes = this.subMeshes.slice();
  22108. this.setPositionsForCPUSkinning();
  22109. this.subMeshes = submeshes;
  22110. }
  22111. if (!this._sourceNormals) {
  22112. this.setNormalsForCPUSkinning();
  22113. }
  22114. // positionsData checks for not being Float32Array will only pass at most once
  22115. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22116. if (!(positionsData instanceof Float32Array)) {
  22117. positionsData = new Float32Array(positionsData);
  22118. }
  22119. // normalsData checks for not being Float32Array will only pass at most once
  22120. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22121. if (!(normalsData instanceof Float32Array)) {
  22122. normalsData = new Float32Array(normalsData);
  22123. }
  22124. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22125. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22126. var needExtras = this.numBoneInfluencers > 4;
  22127. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22128. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22129. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22130. var tempVector3 = BABYLON.Vector3.Zero();
  22131. var finalMatrix = new BABYLON.Matrix();
  22132. var tempMatrix = new BABYLON.Matrix();
  22133. var matWeightIdx = 0;
  22134. var inf;
  22135. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22136. var weight;
  22137. for (inf = 0; inf < 4; inf++) {
  22138. weight = matricesWeightsData[matWeightIdx + inf];
  22139. if (weight > 0) {
  22140. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22141. finalMatrix.addToSelf(tempMatrix);
  22142. }
  22143. else
  22144. break;
  22145. }
  22146. if (needExtras) {
  22147. for (inf = 0; inf < 4; inf++) {
  22148. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22149. if (weight > 0) {
  22150. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22151. finalMatrix.addToSelf(tempMatrix);
  22152. }
  22153. else
  22154. break;
  22155. }
  22156. }
  22157. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22158. tempVector3.toArray(positionsData, index);
  22159. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22160. tempVector3.toArray(normalsData, index);
  22161. finalMatrix.reset();
  22162. }
  22163. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22164. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22165. return this;
  22166. };
  22167. // Tools
  22168. /**
  22169. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22170. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22171. */
  22172. Mesh.MinMax = function (meshes) {
  22173. var minVector = null;
  22174. var maxVector = null;
  22175. meshes.forEach(function (mesh, index, array) {
  22176. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22177. if (!minVector) {
  22178. minVector = boundingBox.minimumWorld;
  22179. maxVector = boundingBox.maximumWorld;
  22180. }
  22181. else {
  22182. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22183. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22184. }
  22185. });
  22186. return {
  22187. min: minVector,
  22188. max: maxVector
  22189. };
  22190. };
  22191. /**
  22192. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22193. */
  22194. Mesh.Center = function (meshesOrMinMaxVector) {
  22195. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22196. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22197. };
  22198. /**
  22199. * Merge the array of meshes into a single mesh for performance reasons.
  22200. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22201. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22202. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22203. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22204. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22205. */
  22206. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22207. if (disposeSource === void 0) { disposeSource = true; }
  22208. var index;
  22209. if (!allow32BitsIndices) {
  22210. var totalVertices = 0;
  22211. // Counting vertices
  22212. for (index = 0; index < meshes.length; index++) {
  22213. if (meshes[index]) {
  22214. totalVertices += meshes[index].getTotalVertices();
  22215. if (totalVertices > 65536) {
  22216. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22217. return null;
  22218. }
  22219. }
  22220. }
  22221. }
  22222. // Merge
  22223. var vertexData;
  22224. var otherVertexData;
  22225. var indiceArray = new Array();
  22226. var source;
  22227. for (index = 0; index < meshes.length; index++) {
  22228. if (meshes[index]) {
  22229. meshes[index].computeWorldMatrix(true);
  22230. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22231. otherVertexData.transform(meshes[index].getWorldMatrix());
  22232. if (vertexData) {
  22233. vertexData.merge(otherVertexData);
  22234. }
  22235. else {
  22236. vertexData = otherVertexData;
  22237. source = meshes[index];
  22238. }
  22239. if (subdivideWithSubMeshes) {
  22240. indiceArray.push(meshes[index].getTotalIndices());
  22241. }
  22242. }
  22243. }
  22244. if (!meshSubclass) {
  22245. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22246. }
  22247. vertexData.applyToMesh(meshSubclass);
  22248. // Setting properties
  22249. meshSubclass.material = source.material;
  22250. meshSubclass.checkCollisions = source.checkCollisions;
  22251. // Cleaning
  22252. if (disposeSource) {
  22253. for (index = 0; index < meshes.length; index++) {
  22254. if (meshes[index]) {
  22255. meshes[index].dispose();
  22256. }
  22257. }
  22258. }
  22259. // Subdivide
  22260. if (subdivideWithSubMeshes) {
  22261. //-- Suppresions du submesh global
  22262. meshSubclass.releaseSubMeshes();
  22263. index = 0;
  22264. var offset = 0;
  22265. //-- aplique la subdivision en fonction du tableau d'indices
  22266. while (index < indiceArray.length) {
  22267. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22268. offset += indiceArray[index];
  22269. index++;
  22270. }
  22271. }
  22272. return meshSubclass;
  22273. };
  22274. return Mesh;
  22275. }(BABYLON.AbstractMesh));
  22276. // Consts
  22277. Mesh._FRONTSIDE = 0;
  22278. Mesh._BACKSIDE = 1;
  22279. Mesh._DOUBLESIDE = 2;
  22280. Mesh._DEFAULTSIDE = 0;
  22281. Mesh._NO_CAP = 0;
  22282. Mesh._CAP_START = 1;
  22283. Mesh._CAP_END = 2;
  22284. Mesh._CAP_ALL = 3;
  22285. BABYLON.Mesh = Mesh;
  22286. })(BABYLON || (BABYLON = {}));
  22287. //# sourceMappingURL=babylon.mesh.js.map
  22288. var BABYLON;
  22289. (function (BABYLON) {
  22290. var BaseSubMesh = (function () {
  22291. function BaseSubMesh() {
  22292. }
  22293. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  22294. get: function () {
  22295. return this._materialEffect;
  22296. },
  22297. enumerable: true,
  22298. configurable: true
  22299. });
  22300. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  22301. if (this._materialEffect === effect) {
  22302. return;
  22303. }
  22304. this._materialDefines = defines;
  22305. this._materialEffect = effect;
  22306. };
  22307. return BaseSubMesh;
  22308. }());
  22309. BABYLON.BaseSubMesh = BaseSubMesh;
  22310. var SubMesh = (function (_super) {
  22311. __extends(SubMesh, _super);
  22312. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22313. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22314. var _this = _super.call(this) || this;
  22315. _this.materialIndex = materialIndex;
  22316. _this.verticesStart = verticesStart;
  22317. _this.verticesCount = verticesCount;
  22318. _this.indexStart = indexStart;
  22319. _this.indexCount = indexCount;
  22320. _this._renderId = 0;
  22321. _this._mesh = mesh;
  22322. _this._renderingMesh = renderingMesh || mesh;
  22323. mesh.subMeshes.push(_this);
  22324. _this._trianglePlanes = [];
  22325. _this._id = mesh.subMeshes.length - 1;
  22326. if (createBoundingBox) {
  22327. _this.refreshBoundingInfo();
  22328. mesh.computeWorldMatrix(true);
  22329. }
  22330. return _this;
  22331. }
  22332. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22333. get: function () {
  22334. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22335. },
  22336. enumerable: true,
  22337. configurable: true
  22338. });
  22339. /**
  22340. * Returns the submesh BoudingInfo object.
  22341. */
  22342. SubMesh.prototype.getBoundingInfo = function () {
  22343. if (this.IsGlobal) {
  22344. return this._mesh.getBoundingInfo();
  22345. }
  22346. return this._boundingInfo;
  22347. };
  22348. /**
  22349. * Sets the submesh BoundingInfo.
  22350. * Return the SubMesh.
  22351. */
  22352. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22353. this._boundingInfo = boundingInfo;
  22354. return this;
  22355. };
  22356. /**
  22357. * Returns the mesh of the current submesh.
  22358. */
  22359. SubMesh.prototype.getMesh = function () {
  22360. return this._mesh;
  22361. };
  22362. /**
  22363. * Returns the rendering mesh of the submesh.
  22364. */
  22365. SubMesh.prototype.getRenderingMesh = function () {
  22366. return this._renderingMesh;
  22367. };
  22368. /**
  22369. * Returns the submesh material.
  22370. */
  22371. SubMesh.prototype.getMaterial = function () {
  22372. var rootMaterial = this._renderingMesh.material;
  22373. if (rootMaterial && rootMaterial.getSubMaterial) {
  22374. var multiMaterial = rootMaterial;
  22375. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22376. if (this._currentMaterial !== effectiveMaterial) {
  22377. this._currentMaterial = effectiveMaterial;
  22378. if (this._materialDefines) {
  22379. this._materialDefines.markAllAsDirty();
  22380. }
  22381. }
  22382. return effectiveMaterial;
  22383. }
  22384. if (!rootMaterial) {
  22385. return this._mesh.getScene().defaultMaterial;
  22386. }
  22387. return rootMaterial;
  22388. };
  22389. // Methods
  22390. /**
  22391. * Sets a new updated BoundingInfo object to the submesh.
  22392. * Returns the SubMesh.
  22393. */
  22394. SubMesh.prototype.refreshBoundingInfo = function () {
  22395. this._lastColliderWorldVertices = null;
  22396. if (this.IsGlobal) {
  22397. return;
  22398. }
  22399. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22400. if (!data) {
  22401. this._boundingInfo = this._mesh._boundingInfo;
  22402. return;
  22403. }
  22404. var indices = this._renderingMesh.getIndices();
  22405. var extend;
  22406. //is this the only submesh?
  22407. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22408. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22409. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22410. }
  22411. else {
  22412. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22413. }
  22414. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22415. return this;
  22416. };
  22417. SubMesh.prototype._checkCollision = function (collider) {
  22418. return this.getBoundingInfo()._checkCollision(collider);
  22419. };
  22420. /**
  22421. * Updates the submesh BoundingInfo.
  22422. * Returns the Submesh.
  22423. */
  22424. SubMesh.prototype.updateBoundingInfo = function (world) {
  22425. if (!this.getBoundingInfo()) {
  22426. this.refreshBoundingInfo();
  22427. }
  22428. this.getBoundingInfo().update(world);
  22429. return this;
  22430. };
  22431. /**
  22432. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22433. * Boolean returned.
  22434. */
  22435. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22436. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22437. };
  22438. /**
  22439. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22440. * Boolean returned.
  22441. */
  22442. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22443. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22444. };
  22445. /**
  22446. * Renders the submesh.
  22447. * Returns it.
  22448. */
  22449. SubMesh.prototype.render = function (enableAlphaMode) {
  22450. this._renderingMesh.render(this, enableAlphaMode);
  22451. return this;
  22452. };
  22453. /**
  22454. * Returns a new Index Buffer.
  22455. * Type returned : WebGLBuffer.
  22456. */
  22457. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22458. if (!this._linesIndexBuffer) {
  22459. var linesIndices = [];
  22460. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22461. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22462. }
  22463. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22464. this.linesIndexCount = linesIndices.length;
  22465. }
  22466. return this._linesIndexBuffer;
  22467. };
  22468. /**
  22469. * True is the passed Ray intersects the submesh bounding box.
  22470. * Boolean returned.
  22471. */
  22472. SubMesh.prototype.canIntersects = function (ray) {
  22473. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22474. };
  22475. /**
  22476. * Returns an object IntersectionInfo.
  22477. */
  22478. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22479. var intersectInfo = null;
  22480. // LineMesh first as it's also a Mesh...
  22481. if (this._mesh instanceof BABYLON.LinesMesh) {
  22482. var lineMesh = this._mesh;
  22483. // Line test
  22484. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22485. var p0 = positions[indices[index]];
  22486. var p1 = positions[indices[index + 1]];
  22487. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22488. if (length < 0) {
  22489. continue;
  22490. }
  22491. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22492. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22493. if (fastCheck) {
  22494. break;
  22495. }
  22496. }
  22497. }
  22498. }
  22499. else {
  22500. // Triangles test
  22501. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22502. var p0 = positions[indices[index]];
  22503. var p1 = positions[indices[index + 1]];
  22504. var p2 = positions[indices[index + 2]];
  22505. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22506. if (currentIntersectInfo) {
  22507. if (currentIntersectInfo.distance < 0) {
  22508. continue;
  22509. }
  22510. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22511. intersectInfo = currentIntersectInfo;
  22512. intersectInfo.faceId = index / 3;
  22513. if (fastCheck) {
  22514. break;
  22515. }
  22516. }
  22517. }
  22518. }
  22519. }
  22520. return intersectInfo;
  22521. };
  22522. // Clone
  22523. /**
  22524. * Creates a new Submesh from the passed Mesh.
  22525. */
  22526. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22527. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22528. if (!this.IsGlobal) {
  22529. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22530. }
  22531. return result;
  22532. };
  22533. // Dispose
  22534. /**
  22535. * Disposes the Submesh.
  22536. * Returns nothing.
  22537. */
  22538. SubMesh.prototype.dispose = function () {
  22539. if (this._linesIndexBuffer) {
  22540. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22541. this._linesIndexBuffer = null;
  22542. }
  22543. // Remove from mesh
  22544. var index = this._mesh.subMeshes.indexOf(this);
  22545. this._mesh.subMeshes.splice(index, 1);
  22546. };
  22547. // Statics
  22548. /**
  22549. * Creates a new Submesh from the passed parameters :
  22550. * - materialIndex (integer) : the index of the main mesh material.
  22551. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22552. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22553. * - mesh (Mesh) : the main mesh to create the submesh from.
  22554. * - renderingMesh (optional Mesh) : rendering mesh.
  22555. */
  22556. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22557. var minVertexIndex = Number.MAX_VALUE;
  22558. var maxVertexIndex = -Number.MAX_VALUE;
  22559. renderingMesh = renderingMesh || mesh;
  22560. var indices = renderingMesh.getIndices();
  22561. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22562. var vertexIndex = indices[index];
  22563. if (vertexIndex < minVertexIndex)
  22564. minVertexIndex = vertexIndex;
  22565. if (vertexIndex > maxVertexIndex)
  22566. maxVertexIndex = vertexIndex;
  22567. }
  22568. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22569. };
  22570. return SubMesh;
  22571. }(BaseSubMesh));
  22572. BABYLON.SubMesh = SubMesh;
  22573. })(BABYLON || (BABYLON = {}));
  22574. //# sourceMappingURL=babylon.subMesh.js.map
  22575. var BABYLON;
  22576. (function (BABYLON) {
  22577. var EffectFallbacks = (function () {
  22578. function EffectFallbacks() {
  22579. this._defines = {};
  22580. this._currentRank = 32;
  22581. this._maxRank = -1;
  22582. }
  22583. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22584. if (!this._defines[rank]) {
  22585. if (rank < this._currentRank) {
  22586. this._currentRank = rank;
  22587. }
  22588. if (rank > this._maxRank) {
  22589. this._maxRank = rank;
  22590. }
  22591. this._defines[rank] = new Array();
  22592. }
  22593. this._defines[rank].push(define);
  22594. };
  22595. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22596. this._meshRank = rank;
  22597. this._mesh = mesh;
  22598. if (rank < this._currentRank) {
  22599. this._currentRank = rank;
  22600. }
  22601. if (rank > this._maxRank) {
  22602. this._maxRank = rank;
  22603. }
  22604. };
  22605. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22606. get: function () {
  22607. return this._currentRank <= this._maxRank;
  22608. },
  22609. enumerable: true,
  22610. configurable: true
  22611. });
  22612. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22613. // First we try to switch to CPU skinning
  22614. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22615. this._mesh.computeBonesUsingShaders = false;
  22616. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22617. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22618. var scene = this._mesh.getScene();
  22619. for (var index = 0; index < scene.meshes.length; index++) {
  22620. var otherMesh = scene.meshes[index];
  22621. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22622. otherMesh.computeBonesUsingShaders = false;
  22623. }
  22624. }
  22625. }
  22626. else {
  22627. var currentFallbacks = this._defines[this._currentRank];
  22628. if (currentFallbacks) {
  22629. for (var index = 0; index < currentFallbacks.length; index++) {
  22630. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22631. }
  22632. }
  22633. this._currentRank++;
  22634. }
  22635. return currentDefines;
  22636. };
  22637. return EffectFallbacks;
  22638. }());
  22639. BABYLON.EffectFallbacks = EffectFallbacks;
  22640. var EffectCreationOptions = (function () {
  22641. function EffectCreationOptions() {
  22642. }
  22643. return EffectCreationOptions;
  22644. }());
  22645. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22646. var Effect = (function () {
  22647. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22648. var _this = this;
  22649. this.uniqueId = 0;
  22650. this.onCompileObservable = new BABYLON.Observable();
  22651. this.onErrorObservable = new BABYLON.Observable();
  22652. this.onBindObservable = new BABYLON.Observable();
  22653. this._uniformBuffersNames = {};
  22654. this._isReady = false;
  22655. this._compilationError = "";
  22656. this._valueCache = {};
  22657. this.name = baseName;
  22658. if (attributesNamesOrOptions.attributes) {
  22659. var options = attributesNamesOrOptions;
  22660. this._engine = uniformsNamesOrEngine;
  22661. this._attributesNames = options.attributes;
  22662. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22663. this._samplers = options.samplers;
  22664. this.defines = options.defines;
  22665. this.onError = options.onError;
  22666. this.onCompiled = options.onCompiled;
  22667. this._fallbacks = options.fallbacks;
  22668. this._indexParameters = options.indexParameters;
  22669. if (options.uniformBuffersNames) {
  22670. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22671. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22672. }
  22673. }
  22674. }
  22675. else {
  22676. this._engine = engine;
  22677. this.defines = defines;
  22678. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22679. this._samplers = samplers;
  22680. this._attributesNames = attributesNamesOrOptions;
  22681. this.onError = onError;
  22682. this.onCompiled = onCompiled;
  22683. this._indexParameters = indexParameters;
  22684. this._fallbacks = fallbacks;
  22685. }
  22686. this.uniqueId = Effect._uniqueIdSeed++;
  22687. var vertexSource;
  22688. var fragmentSource;
  22689. if (baseName.vertexElement) {
  22690. vertexSource = document.getElementById(baseName.vertexElement);
  22691. if (!vertexSource) {
  22692. vertexSource = baseName.vertexElement;
  22693. }
  22694. }
  22695. else {
  22696. vertexSource = baseName.vertex || baseName;
  22697. }
  22698. if (baseName.fragmentElement) {
  22699. fragmentSource = document.getElementById(baseName.fragmentElement);
  22700. if (!fragmentSource) {
  22701. fragmentSource = baseName.fragmentElement;
  22702. }
  22703. }
  22704. else {
  22705. fragmentSource = baseName.fragment || baseName;
  22706. }
  22707. this._loadVertexShader(vertexSource, function (vertexCode) {
  22708. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22709. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22710. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22711. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22712. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22713. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22714. });
  22715. });
  22716. });
  22717. });
  22718. });
  22719. });
  22720. }
  22721. Object.defineProperty(Effect.prototype, "key", {
  22722. get: function () {
  22723. return this._key;
  22724. },
  22725. enumerable: true,
  22726. configurable: true
  22727. });
  22728. // Properties
  22729. Effect.prototype.isReady = function () {
  22730. return this._isReady;
  22731. };
  22732. Effect.prototype.getEngine = function () {
  22733. return this._engine;
  22734. };
  22735. Effect.prototype.getProgram = function () {
  22736. return this._program;
  22737. };
  22738. Effect.prototype.getAttributesNames = function () {
  22739. return this._attributesNames;
  22740. };
  22741. Effect.prototype.getAttributeLocation = function (index) {
  22742. return this._attributes[index];
  22743. };
  22744. Effect.prototype.getAttributeLocationByName = function (name) {
  22745. var index = this._attributesNames.indexOf(name);
  22746. return this._attributes[index];
  22747. };
  22748. Effect.prototype.getAttributesCount = function () {
  22749. return this._attributes.length;
  22750. };
  22751. Effect.prototype.getUniformIndex = function (uniformName) {
  22752. return this._uniformsNames.indexOf(uniformName);
  22753. };
  22754. Effect.prototype.getUniform = function (uniformName) {
  22755. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22756. };
  22757. Effect.prototype.getSamplers = function () {
  22758. return this._samplers;
  22759. };
  22760. Effect.prototype.getCompilationError = function () {
  22761. return this._compilationError;
  22762. };
  22763. Effect.prototype.getVertexShaderSource = function () {
  22764. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22765. };
  22766. Effect.prototype.getFragmentShaderSource = function () {
  22767. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22768. };
  22769. // Methods
  22770. Effect.prototype.executeWhenCompiled = function (func) {
  22771. var _this = this;
  22772. if (this.isReady()) {
  22773. func(this);
  22774. return;
  22775. }
  22776. var observer = this.onCompileObservable.add(function (effect) {
  22777. _this.onCompileObservable.remove(observer);
  22778. func(effect);
  22779. });
  22780. };
  22781. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22782. // DOM element ?
  22783. if (vertex instanceof HTMLElement) {
  22784. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22785. callback(vertexCode);
  22786. return;
  22787. }
  22788. // Base64 encoded ?
  22789. if (vertex.substr(0, 7) === "base64:") {
  22790. var vertexBinary = window.atob(vertex.substr(7));
  22791. callback(vertexBinary);
  22792. return;
  22793. }
  22794. // Is in local store ?
  22795. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22796. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22797. return;
  22798. }
  22799. var vertexShaderUrl;
  22800. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22801. vertexShaderUrl = vertex;
  22802. }
  22803. else {
  22804. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22805. }
  22806. // Vertex shader
  22807. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22808. };
  22809. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22810. // DOM element ?
  22811. if (fragment instanceof HTMLElement) {
  22812. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22813. callback(fragmentCode);
  22814. return;
  22815. }
  22816. // Base64 encoded ?
  22817. if (fragment.substr(0, 7) === "base64:") {
  22818. var fragmentBinary = window.atob(fragment.substr(7));
  22819. callback(fragmentBinary);
  22820. return;
  22821. }
  22822. // Is in local store ?
  22823. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22824. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22825. return;
  22826. }
  22827. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22828. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22829. return;
  22830. }
  22831. var fragmentShaderUrl;
  22832. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22833. fragmentShaderUrl = fragment;
  22834. }
  22835. else {
  22836. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22837. }
  22838. // Fragment shader
  22839. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22840. };
  22841. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22842. // Rebuild shaders source code
  22843. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22844. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22845. vertexCode = prefix + vertexCode;
  22846. fragmentCode = prefix + fragmentCode;
  22847. // Number lines of shaders source code
  22848. var i = 2;
  22849. var regex = /\n/gm;
  22850. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22851. i = 2;
  22852. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22853. // Dump shaders name and formatted source code
  22854. if (this.name.vertexElement) {
  22855. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22856. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22857. }
  22858. else if (this.name.vertex) {
  22859. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22860. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22861. }
  22862. else {
  22863. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22864. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22865. }
  22866. };
  22867. ;
  22868. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22869. var preparedSourceCode = this._processPrecision(sourceCode);
  22870. if (this._engine.webGLVersion == 1) {
  22871. callback(preparedSourceCode);
  22872. return;
  22873. }
  22874. // Already converted
  22875. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22876. callback(preparedSourceCode.replace("#version 300 es", ""));
  22877. return;
  22878. }
  22879. // Remove extensions
  22880. // #extension GL_OES_standard_derivatives : enable
  22881. // #extension GL_EXT_shader_texture_lod : enable
  22882. // #extension GL_EXT_frag_depth : enable
  22883. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22884. var result = preparedSourceCode.replace(regex, "");
  22885. // Migrate to GLSL v300
  22886. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22887. result = result.replace(/attribute[ \t]/g, "in ");
  22888. result = result.replace(/[ \t]attribute/g, " in");
  22889. if (isFragment) {
  22890. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22891. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22892. result = result.replace(/texture2D\(/g, "texture(");
  22893. result = result.replace(/textureCube\(/g, "texture(");
  22894. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22895. result = result.replace(/gl_FragColor/g, "glFragColor");
  22896. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22897. }
  22898. callback(result);
  22899. };
  22900. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22901. var _this = this;
  22902. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22903. var match = regex.exec(sourceCode);
  22904. var returnValue = new String(sourceCode);
  22905. while (match != null) {
  22906. var includeFile = match[1];
  22907. // Uniform declaration
  22908. if (includeFile.indexOf("__decl__") !== -1) {
  22909. includeFile = includeFile.replace(/__decl__/, "");
  22910. if (this._engine.webGLVersion != 1) {
  22911. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22912. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22913. }
  22914. includeFile = includeFile + "Declaration";
  22915. }
  22916. if (Effect.IncludesShadersStore[includeFile]) {
  22917. // Substitution
  22918. var includeContent = Effect.IncludesShadersStore[includeFile];
  22919. if (match[2]) {
  22920. var splits = match[3].split(",");
  22921. for (var index = 0; index < splits.length; index += 2) {
  22922. var source = new RegExp(splits[index], "g");
  22923. var dest = splits[index + 1];
  22924. includeContent = includeContent.replace(source, dest);
  22925. }
  22926. }
  22927. if (match[4]) {
  22928. var indexString = match[5];
  22929. if (indexString.indexOf("..") !== -1) {
  22930. var indexSplits = indexString.split("..");
  22931. var minIndex = parseInt(indexSplits[0]);
  22932. var maxIndex = parseInt(indexSplits[1]);
  22933. var sourceIncludeContent = includeContent.slice(0);
  22934. includeContent = "";
  22935. if (isNaN(maxIndex)) {
  22936. maxIndex = this._indexParameters[indexSplits[1]];
  22937. }
  22938. for (var i = minIndex; i < maxIndex; i++) {
  22939. if (this._engine.webGLVersion === 1) {
  22940. // Ubo replacement
  22941. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22942. return p1 + "{X}";
  22943. });
  22944. }
  22945. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22946. }
  22947. }
  22948. else {
  22949. if (this._engine.webGLVersion === 1) {
  22950. // Ubo replacement
  22951. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22952. return p1 + "{X}";
  22953. });
  22954. }
  22955. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22956. }
  22957. }
  22958. // Replace
  22959. returnValue = returnValue.replace(match[0], includeContent);
  22960. }
  22961. else {
  22962. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22963. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22964. Effect.IncludesShadersStore[includeFile] = fileContent;
  22965. _this._processIncludes(returnValue, callback);
  22966. });
  22967. return;
  22968. }
  22969. match = regex.exec(sourceCode);
  22970. }
  22971. callback(returnValue);
  22972. };
  22973. Effect.prototype._processPrecision = function (source) {
  22974. if (source.indexOf("precision highp float") === -1) {
  22975. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22976. source = "precision mediump float;\n" + source;
  22977. }
  22978. else {
  22979. source = "precision highp float;\n" + source;
  22980. }
  22981. }
  22982. else {
  22983. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22984. source = source.replace("precision highp float", "precision mediump float");
  22985. }
  22986. }
  22987. return source;
  22988. };
  22989. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22990. try {
  22991. var engine = this._engine;
  22992. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22993. if (engine.webGLVersion > 1) {
  22994. for (var name in this._uniformBuffersNames) {
  22995. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  22996. }
  22997. }
  22998. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22999. this._attributes = engine.getAttributes(this._program, attributesNames);
  23000. var index;
  23001. for (index = 0; index < this._samplers.length; index++) {
  23002. var sampler = this.getUniform(this._samplers[index]);
  23003. if (sampler == null) {
  23004. this._samplers.splice(index, 1);
  23005. index--;
  23006. }
  23007. }
  23008. engine.bindSamplers(this);
  23009. this._compilationError = "";
  23010. this._isReady = true;
  23011. if (this.onCompiled) {
  23012. this.onCompiled(this);
  23013. }
  23014. this.onCompileObservable.notifyObservers(this);
  23015. }
  23016. catch (e) {
  23017. this._compilationError = e.message;
  23018. // Let's go through fallbacks then
  23019. BABYLON.Tools.Error("Unable to compile effect:");
  23020. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  23021. return " " + uniform;
  23022. }));
  23023. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  23024. return " " + attribute;
  23025. }));
  23026. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  23027. BABYLON.Tools.Error("Error: " + this._compilationError);
  23028. if (fallbacks && fallbacks.isMoreFallbacks) {
  23029. BABYLON.Tools.Error("Trying next fallback.");
  23030. defines = fallbacks.reduce(defines);
  23031. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23032. }
  23033. else {
  23034. if (this.onError) {
  23035. this.onError(this, this._compilationError);
  23036. }
  23037. this.onErrorObservable.notifyObservers(this);
  23038. }
  23039. }
  23040. };
  23041. Object.defineProperty(Effect.prototype, "isSupported", {
  23042. get: function () {
  23043. return this._compilationError === "";
  23044. },
  23045. enumerable: true,
  23046. configurable: true
  23047. });
  23048. Effect.prototype._bindTexture = function (channel, texture) {
  23049. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23050. };
  23051. Effect.prototype.setTexture = function (channel, texture) {
  23052. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23053. };
  23054. Effect.prototype.setTextureArray = function (channel, textures) {
  23055. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23056. var initialPos = this._samplers.indexOf(channel);
  23057. for (var index = 1; index < textures.length; index++) {
  23058. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23059. }
  23060. }
  23061. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23062. };
  23063. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23064. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23065. };
  23066. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23067. var cache = this._valueCache[uniformName];
  23068. var flag = matrix.updateFlag;
  23069. if (cache !== undefined && cache === flag) {
  23070. return false;
  23071. }
  23072. this._valueCache[uniformName] = flag;
  23073. return true;
  23074. };
  23075. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23076. var cache = this._valueCache[uniformName];
  23077. if (!cache) {
  23078. cache = [x, y];
  23079. this._valueCache[uniformName] = cache;
  23080. return true;
  23081. }
  23082. var changed = false;
  23083. if (cache[0] !== x) {
  23084. cache[0] = x;
  23085. changed = true;
  23086. }
  23087. if (cache[1] !== y) {
  23088. cache[1] = y;
  23089. changed = true;
  23090. }
  23091. return changed;
  23092. };
  23093. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23094. var cache = this._valueCache[uniformName];
  23095. if (!cache) {
  23096. cache = [x, y, z];
  23097. this._valueCache[uniformName] = cache;
  23098. return true;
  23099. }
  23100. var changed = false;
  23101. if (cache[0] !== x) {
  23102. cache[0] = x;
  23103. changed = true;
  23104. }
  23105. if (cache[1] !== y) {
  23106. cache[1] = y;
  23107. changed = true;
  23108. }
  23109. if (cache[2] !== z) {
  23110. cache[2] = z;
  23111. changed = true;
  23112. }
  23113. return changed;
  23114. };
  23115. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23116. var cache = this._valueCache[uniformName];
  23117. if (!cache) {
  23118. cache = [x, y, z, w];
  23119. this._valueCache[uniformName] = cache;
  23120. return true;
  23121. }
  23122. var changed = false;
  23123. if (cache[0] !== x) {
  23124. cache[0] = x;
  23125. changed = true;
  23126. }
  23127. if (cache[1] !== y) {
  23128. cache[1] = y;
  23129. changed = true;
  23130. }
  23131. if (cache[2] !== z) {
  23132. cache[2] = z;
  23133. changed = true;
  23134. }
  23135. if (cache[3] !== w) {
  23136. cache[3] = w;
  23137. changed = true;
  23138. }
  23139. return changed;
  23140. };
  23141. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  23142. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  23143. return;
  23144. }
  23145. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  23146. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  23147. };
  23148. Effect.prototype.bindUniformBlock = function (blockName, index) {
  23149. this._engine.bindUniformBlock(this._program, blockName, index);
  23150. };
  23151. Effect.prototype.setIntArray = function (uniformName, array) {
  23152. this._valueCache[uniformName] = null;
  23153. this._engine.setIntArray(this.getUniform(uniformName), array);
  23154. return this;
  23155. };
  23156. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23157. this._valueCache[uniformName] = null;
  23158. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23159. return this;
  23160. };
  23161. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23162. this._valueCache[uniformName] = null;
  23163. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23164. return this;
  23165. };
  23166. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23167. this._valueCache[uniformName] = null;
  23168. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23169. return this;
  23170. };
  23171. Effect.prototype.setFloatArray = function (uniformName, array) {
  23172. this._valueCache[uniformName] = null;
  23173. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23174. return this;
  23175. };
  23176. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23177. this._valueCache[uniformName] = null;
  23178. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23179. return this;
  23180. };
  23181. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23182. this._valueCache[uniformName] = null;
  23183. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23184. return this;
  23185. };
  23186. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23187. this._valueCache[uniformName] = null;
  23188. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23189. return this;
  23190. };
  23191. Effect.prototype.setArray = function (uniformName, array) {
  23192. this._valueCache[uniformName] = null;
  23193. this._engine.setArray(this.getUniform(uniformName), array);
  23194. return this;
  23195. };
  23196. Effect.prototype.setArray2 = function (uniformName, array) {
  23197. this._valueCache[uniformName] = null;
  23198. this._engine.setArray2(this.getUniform(uniformName), array);
  23199. return this;
  23200. };
  23201. Effect.prototype.setArray3 = function (uniformName, array) {
  23202. this._valueCache[uniformName] = null;
  23203. this._engine.setArray3(this.getUniform(uniformName), array);
  23204. return this;
  23205. };
  23206. Effect.prototype.setArray4 = function (uniformName, array) {
  23207. this._valueCache[uniformName] = null;
  23208. this._engine.setArray4(this.getUniform(uniformName), array);
  23209. return this;
  23210. };
  23211. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23212. if (!matrices) {
  23213. return;
  23214. }
  23215. this._valueCache[uniformName] = null;
  23216. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23217. return this;
  23218. };
  23219. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23220. if (this._cacheMatrix(uniformName, matrix)) {
  23221. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23222. }
  23223. return this;
  23224. };
  23225. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23226. this._valueCache[uniformName] = null;
  23227. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23228. return this;
  23229. };
  23230. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23231. this._valueCache[uniformName] = null;
  23232. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23233. return this;
  23234. };
  23235. Effect.prototype.setFloat = function (uniformName, value) {
  23236. var cache = this._valueCache[uniformName];
  23237. if (cache !== undefined && cache === value)
  23238. return this;
  23239. this._valueCache[uniformName] = value;
  23240. this._engine.setFloat(this.getUniform(uniformName), value);
  23241. return this;
  23242. };
  23243. Effect.prototype.setBool = function (uniformName, bool) {
  23244. var cache = this._valueCache[uniformName];
  23245. if (cache !== undefined && cache === bool)
  23246. return this;
  23247. this._valueCache[uniformName] = bool;
  23248. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23249. return this;
  23250. };
  23251. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23252. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23253. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23254. }
  23255. return this;
  23256. };
  23257. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23258. if (this._cacheFloat2(uniformName, x, y)) {
  23259. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23260. }
  23261. return this;
  23262. };
  23263. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23264. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23265. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23266. }
  23267. return this;
  23268. };
  23269. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23270. if (this._cacheFloat3(uniformName, x, y, z)) {
  23271. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23272. }
  23273. return this;
  23274. };
  23275. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23276. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23277. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23278. }
  23279. return this;
  23280. };
  23281. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23282. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23283. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23284. }
  23285. return this;
  23286. };
  23287. Effect.prototype.setColor3 = function (uniformName, color3) {
  23288. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23289. this._engine.setColor3(this.getUniform(uniformName), color3);
  23290. }
  23291. return this;
  23292. };
  23293. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23294. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23295. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23296. }
  23297. return this;
  23298. };
  23299. Effect.prototype._recombineShader = function (node) {
  23300. if (node.define) {
  23301. if (node.condition) {
  23302. var defineIndex = this.defines.indexOf("#define " + node.define);
  23303. if (defineIndex === -1) {
  23304. return null;
  23305. }
  23306. var nextComma = this.defines.indexOf("\n", defineIndex);
  23307. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23308. var condition = defineValue + node.condition;
  23309. if (!eval(condition)) {
  23310. return null;
  23311. }
  23312. }
  23313. else if (node.ndef) {
  23314. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23315. return null;
  23316. }
  23317. }
  23318. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23319. return null;
  23320. }
  23321. }
  23322. var result = "";
  23323. for (var index = 0; index < node.children.length; index++) {
  23324. var line = node.children[index];
  23325. if (line.children) {
  23326. var combined = this._recombineShader(line);
  23327. if (combined !== null) {
  23328. result += combined + "\r\n";
  23329. }
  23330. continue;
  23331. }
  23332. if (line.length > 0) {
  23333. result += line + "\r\n";
  23334. }
  23335. }
  23336. return result;
  23337. };
  23338. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23339. var root = {
  23340. children: []
  23341. };
  23342. var currentNode = root;
  23343. var lines = shaderString.split("\n");
  23344. for (var index = 0; index < lines.length; index++) {
  23345. var line = lines[index].trim();
  23346. // #ifdef
  23347. var pos = line.indexOf("#ifdef ");
  23348. if (pos !== -1) {
  23349. var define = line.substr(pos + 7);
  23350. var newNode = {
  23351. condition: null,
  23352. ndef: false,
  23353. define: define,
  23354. children: [],
  23355. parent: currentNode
  23356. };
  23357. currentNode.children.push(newNode);
  23358. currentNode = newNode;
  23359. continue;
  23360. }
  23361. // #ifndef
  23362. var pos = line.indexOf("#ifndef ");
  23363. if (pos !== -1) {
  23364. var define = line.substr(pos + 8);
  23365. newNode = {
  23366. condition: null,
  23367. define: define,
  23368. ndef: true,
  23369. children: [],
  23370. parent: currentNode
  23371. };
  23372. currentNode.children.push(newNode);
  23373. currentNode = newNode;
  23374. continue;
  23375. }
  23376. // #if
  23377. var pos = line.indexOf("#if ");
  23378. if (pos !== -1) {
  23379. var define = line.substr(pos + 4).trim();
  23380. var conditionPos = define.indexOf(" ");
  23381. newNode = {
  23382. condition: define.substr(conditionPos + 1),
  23383. define: define.substr(0, conditionPos),
  23384. ndef: false,
  23385. children: [],
  23386. parent: currentNode
  23387. };
  23388. currentNode.children.push(newNode);
  23389. currentNode = newNode;
  23390. continue;
  23391. }
  23392. // #endif
  23393. pos = line.indexOf("#endif");
  23394. if (pos !== -1) {
  23395. currentNode = currentNode.parent;
  23396. continue;
  23397. }
  23398. currentNode.children.push(line);
  23399. }
  23400. // Recombine
  23401. return this._recombineShader(root);
  23402. };
  23403. return Effect;
  23404. }());
  23405. Effect._uniqueIdSeed = 0;
  23406. Effect._baseCache = {};
  23407. // Statics
  23408. Effect.ShadersStore = {};
  23409. Effect.IncludesShadersStore = {};
  23410. BABYLON.Effect = Effect;
  23411. })(BABYLON || (BABYLON = {}));
  23412. //# sourceMappingURL=babylon.effect.js.map
  23413. var BABYLON;
  23414. (function (BABYLON) {
  23415. var MaterialHelper = (function () {
  23416. function MaterialHelper() {
  23417. }
  23418. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23419. if (defines._areMiscDirty) {
  23420. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23421. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23422. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23423. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23424. }
  23425. };
  23426. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  23427. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  23428. var changed = false;
  23429. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23430. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23431. changed = true;
  23432. }
  23433. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  23434. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23435. changed = true;
  23436. }
  23437. if (defines["INSTANCES"] !== useInstances) {
  23438. defines["INSTANCES"] = useInstances;
  23439. changed = true;
  23440. }
  23441. if (changed) {
  23442. defines.markAsUnprocessed();
  23443. }
  23444. };
  23445. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23446. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23447. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23448. return false;
  23449. }
  23450. defines._normals = defines._needNormals;
  23451. defines._uvs = defines._needUVs;
  23452. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23453. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23454. defines["TANGENT"] = true;
  23455. }
  23456. if (defines._needUVs) {
  23457. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23458. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23459. }
  23460. else {
  23461. defines["UV1"] = false;
  23462. defines["UV2"] = false;
  23463. }
  23464. if (useVertexColor) {
  23465. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23466. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23467. }
  23468. if (useBones) {
  23469. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23470. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23471. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23472. }
  23473. else {
  23474. defines["NUM_BONE_INFLUENCERS"] = 0;
  23475. defines["BonesPerMesh"] = 0;
  23476. }
  23477. }
  23478. if (useMorphTargets) {
  23479. if (mesh.morphTargetManager) {
  23480. var manager = mesh.morphTargetManager;
  23481. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23482. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23483. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23484. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23485. }
  23486. else {
  23487. defines["MORPHTARGETS_TANGENT"] = false;
  23488. defines["MORPHTARGETS_NORMAL"] = false;
  23489. defines["MORPHTARGETS"] = false;
  23490. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23491. }
  23492. }
  23493. return true;
  23494. };
  23495. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23496. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23497. if (disableLighting === void 0) { disableLighting = false; }
  23498. if (!defines._areLightsDirty) {
  23499. return defines._needNormals;
  23500. }
  23501. var lightIndex = 0;
  23502. var needNormals = false;
  23503. var needRebuild = false;
  23504. var lightmapMode = false;
  23505. var shadowEnabled = false;
  23506. var specularEnabled = false;
  23507. if (scene.lightsEnabled && !disableLighting) {
  23508. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23509. var light = _a[_i];
  23510. needNormals = true;
  23511. if (defines["LIGHT" + lightIndex] === undefined) {
  23512. needRebuild = true;
  23513. }
  23514. defines["LIGHT" + lightIndex] = true;
  23515. defines["SPOTLIGHT" + lightIndex] = false;
  23516. defines["HEMILIGHT" + lightIndex] = false;
  23517. defines["POINTLIGHT" + lightIndex] = false;
  23518. defines["DIRLIGHT" + lightIndex] = false;
  23519. var type;
  23520. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23521. type = "SPOTLIGHT" + lightIndex;
  23522. }
  23523. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23524. type = "HEMILIGHT" + lightIndex;
  23525. }
  23526. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23527. type = "POINTLIGHT" + lightIndex;
  23528. }
  23529. else {
  23530. type = "DIRLIGHT" + lightIndex;
  23531. }
  23532. defines[type] = true;
  23533. // Specular
  23534. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23535. specularEnabled = true;
  23536. }
  23537. // Shadows
  23538. defines["SHADOW" + lightIndex] = false;
  23539. defines["SHADOWPCF" + lightIndex] = false;
  23540. defines["SHADOWESM" + lightIndex] = false;
  23541. defines["SHADOWCUBE" + lightIndex] = false;
  23542. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23543. var shadowGenerator = light.getShadowGenerator();
  23544. if (shadowGenerator) {
  23545. shadowEnabled = true;
  23546. shadowGenerator.prepareDefines(defines, lightIndex);
  23547. }
  23548. }
  23549. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23550. lightmapMode = true;
  23551. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23552. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23553. }
  23554. else {
  23555. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23556. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23557. }
  23558. lightIndex++;
  23559. if (lightIndex === maxSimultaneousLights)
  23560. break;
  23561. }
  23562. }
  23563. defines["SPECULARTERM"] = specularEnabled;
  23564. defines["SHADOWS"] = shadowEnabled;
  23565. // Resetting all other lights if any
  23566. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23567. if (defines["LIGHT" + index] !== undefined) {
  23568. defines["LIGHT" + index] = false;
  23569. defines["HEMILIGHT" + lightIndex] = false;
  23570. defines["POINTLIGHT" + lightIndex] = false;
  23571. defines["DIRLIGHT" + lightIndex] = false;
  23572. defines["SPOTLIGHT" + lightIndex] = false;
  23573. defines["SHADOW" + lightIndex] = false;
  23574. }
  23575. }
  23576. var caps = scene.getEngine().getCaps();
  23577. if (defines["SHADOWFLOAT"] === undefined) {
  23578. needRebuild = true;
  23579. }
  23580. defines["SHADOWFLOAT"] = shadowEnabled &&
  23581. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  23582. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  23583. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23584. if (needRebuild) {
  23585. defines.rebuild();
  23586. }
  23587. return needNormals;
  23588. };
  23589. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23590. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23591. var uniformsList, uniformBuffersList, samplersList, defines;
  23592. if (uniformsListOrOptions.uniformsNames) {
  23593. var options = uniformsListOrOptions;
  23594. uniformsList = options.uniformsNames;
  23595. uniformBuffersList = options.uniformBuffersNames;
  23596. samplersList = options.samplers;
  23597. defines = options.defines;
  23598. maxSimultaneousLights = options.maxSimultaneousLights;
  23599. }
  23600. else {
  23601. uniformsList = uniformsListOrOptions;
  23602. }
  23603. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23604. if (!defines["LIGHT" + lightIndex]) {
  23605. break;
  23606. }
  23607. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  23608. if (uniformBuffersList) {
  23609. uniformBuffersList.push("Light" + lightIndex);
  23610. }
  23611. samplersList.push("shadowSampler" + lightIndex);
  23612. }
  23613. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23614. uniformsList.push("morphTargetInfluences");
  23615. }
  23616. };
  23617. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23618. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23619. if (!defines["SHADOWS"]) {
  23620. return;
  23621. }
  23622. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23623. if (!defines["LIGHT" + lightIndex]) {
  23624. break;
  23625. }
  23626. if (lightIndex > 0) {
  23627. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23628. }
  23629. if (defines["SHADOW" + lightIndex]) {
  23630. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23631. }
  23632. if (defines["SHADOWPCF" + lightIndex]) {
  23633. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23634. }
  23635. if (defines["SHADOWESM" + lightIndex]) {
  23636. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23637. }
  23638. }
  23639. };
  23640. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23641. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23642. if (influencers > 0) {
  23643. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23644. var manager = mesh.morphTargetManager;
  23645. var normal = manager.supportsNormals && defines["NORMAL"];
  23646. var tangent = manager.supportsTangents && defines["TANGENT"];
  23647. for (var index = 0; index < influencers; index++) {
  23648. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23649. if (normal) {
  23650. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23651. }
  23652. if (tangent) {
  23653. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23654. }
  23655. if (attribs.length > maxAttributesCount) {
  23656. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23657. }
  23658. }
  23659. }
  23660. };
  23661. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23662. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23663. fallbacks.addCPUSkinningFallback(0, mesh);
  23664. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23665. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23666. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23667. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23668. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23669. }
  23670. }
  23671. };
  23672. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23673. if (defines["INSTANCES"]) {
  23674. attribs.push("world0");
  23675. attribs.push("world1");
  23676. attribs.push("world2");
  23677. attribs.push("world3");
  23678. }
  23679. };
  23680. // Bindings
  23681. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  23682. if (light.shadowEnabled && mesh.receiveShadows) {
  23683. var shadowGenerator = light.getShadowGenerator();
  23684. if (shadowGenerator) {
  23685. shadowGenerator.bindShadowLight(lightIndex, effect);
  23686. }
  23687. }
  23688. };
  23689. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23690. light.transferToEffect(effect, lightIndex + "");
  23691. };
  23692. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  23693. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23694. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  23695. var lightIndex = 0;
  23696. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23697. var light = _a[_i];
  23698. var scaledIntensity = light.getScaledIntensity();
  23699. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23700. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23701. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  23702. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  23703. if (defines["SPECULARTERM"]) {
  23704. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  23705. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23706. }
  23707. // Shadows
  23708. if (scene.shadowsEnabled) {
  23709. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  23710. }
  23711. light._uniformBuffer.update();
  23712. lightIndex++;
  23713. if (lightIndex === maxSimultaneousLights)
  23714. break;
  23715. }
  23716. };
  23717. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23718. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23719. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23720. effect.setColor3("vFogColor", scene.fogColor);
  23721. }
  23722. };
  23723. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23724. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23725. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23726. if (matrices) {
  23727. effect.setMatrices("mBones", matrices);
  23728. }
  23729. }
  23730. };
  23731. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23732. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23733. return;
  23734. }
  23735. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23736. };
  23737. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23738. if (defines["LOGARITHMICDEPTH"]) {
  23739. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23740. }
  23741. };
  23742. MaterialHelper.BindClipPlane = function (effect, scene) {
  23743. if (scene.clipPlane) {
  23744. var clipPlane = scene.clipPlane;
  23745. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23746. }
  23747. };
  23748. return MaterialHelper;
  23749. }());
  23750. BABYLON.MaterialHelper = MaterialHelper;
  23751. })(BABYLON || (BABYLON = {}));
  23752. //# sourceMappingURL=babylon.materialHelper.js.map
  23753. var BABYLON;
  23754. (function (BABYLON) {
  23755. var MaterialDefines = (function () {
  23756. function MaterialDefines() {
  23757. this._isDirty = true;
  23758. this._areLightsDirty = true;
  23759. this._areAttributesDirty = true;
  23760. this._areTexturesDirty = true;
  23761. this._areFresnelDirty = true;
  23762. this._areMiscDirty = true;
  23763. this._areImageProcessingDirty = true;
  23764. this._normals = false;
  23765. this._uvs = false;
  23766. this._needNormals = false;
  23767. this._needUVs = false;
  23768. }
  23769. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23770. get: function () {
  23771. return this._isDirty;
  23772. },
  23773. enumerable: true,
  23774. configurable: true
  23775. });
  23776. MaterialDefines.prototype.markAsProcessed = function () {
  23777. this._isDirty = false;
  23778. this._areAttributesDirty = false;
  23779. this._areTexturesDirty = false;
  23780. this._areFresnelDirty = false;
  23781. this._areLightsDirty = false;
  23782. this._areMiscDirty = false;
  23783. this._areImageProcessingDirty = false;
  23784. };
  23785. MaterialDefines.prototype.markAsUnprocessed = function () {
  23786. this._isDirty = true;
  23787. };
  23788. MaterialDefines.prototype.markAllAsDirty = function () {
  23789. this._areTexturesDirty = true;
  23790. this._areAttributesDirty = true;
  23791. this._areLightsDirty = true;
  23792. this._areFresnelDirty = true;
  23793. this._areMiscDirty = true;
  23794. this._areImageProcessingDirty = true;
  23795. this._isDirty = true;
  23796. };
  23797. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  23798. this._areImageProcessingDirty = true;
  23799. this._isDirty = true;
  23800. };
  23801. MaterialDefines.prototype.markAsLightDirty = function () {
  23802. this._areLightsDirty = true;
  23803. this._isDirty = true;
  23804. };
  23805. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23806. this._areAttributesDirty = true;
  23807. this._isDirty = true;
  23808. };
  23809. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23810. this._areTexturesDirty = true;
  23811. this._isDirty = true;
  23812. };
  23813. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23814. this._areFresnelDirty = true;
  23815. this._isDirty = true;
  23816. };
  23817. MaterialDefines.prototype.markAsMiscDirty = function () {
  23818. this._areMiscDirty = true;
  23819. this._isDirty = true;
  23820. };
  23821. MaterialDefines.prototype.rebuild = function () {
  23822. if (this._keys) {
  23823. delete this._keys;
  23824. }
  23825. this._keys = [];
  23826. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23827. var key = _a[_i];
  23828. if (key[0] === "_") {
  23829. continue;
  23830. }
  23831. this._keys.push(key);
  23832. }
  23833. };
  23834. MaterialDefines.prototype.isEqual = function (other) {
  23835. if (this._keys.length !== other._keys.length) {
  23836. return false;
  23837. }
  23838. for (var index = 0; index < this._keys.length; index++) {
  23839. var prop = this._keys[index];
  23840. if (this[prop] !== other[prop]) {
  23841. return false;
  23842. }
  23843. }
  23844. return true;
  23845. };
  23846. MaterialDefines.prototype.cloneTo = function (other) {
  23847. if (this._keys.length !== other._keys.length) {
  23848. other._keys = this._keys.slice(0);
  23849. }
  23850. for (var index = 0; index < this._keys.length; index++) {
  23851. var prop = this._keys[index];
  23852. other[prop] = this[prop];
  23853. }
  23854. };
  23855. MaterialDefines.prototype.reset = function () {
  23856. for (var index = 0; index < this._keys.length; index++) {
  23857. var prop = this._keys[index];
  23858. if (typeof (this[prop]) === "number") {
  23859. this[prop] = 0;
  23860. }
  23861. else {
  23862. this[prop] = false;
  23863. }
  23864. }
  23865. };
  23866. MaterialDefines.prototype.toString = function () {
  23867. var result = "";
  23868. for (var index = 0; index < this._keys.length; index++) {
  23869. var prop = this._keys[index];
  23870. var value = this[prop];
  23871. if (typeof (value) === "number") {
  23872. result += "#define " + prop + " " + this[prop] + "\n";
  23873. }
  23874. else if (value) {
  23875. result += "#define " + prop + "\n";
  23876. }
  23877. }
  23878. return result;
  23879. };
  23880. return MaterialDefines;
  23881. }());
  23882. BABYLON.MaterialDefines = MaterialDefines;
  23883. var Material = (function () {
  23884. function Material(name, scene, doNotAdd) {
  23885. this.checkReadyOnEveryCall = false;
  23886. this.checkReadyOnlyOnce = false;
  23887. this.state = "";
  23888. this.alpha = 1.0;
  23889. this._backFaceCulling = true;
  23890. this.doNotSerialize = false;
  23891. this.storeEffectOnSubMeshes = false;
  23892. /**
  23893. * An event triggered when the material is disposed.
  23894. * @type {BABYLON.Observable}
  23895. */
  23896. this.onDisposeObservable = new BABYLON.Observable();
  23897. /**
  23898. * An event triggered when the material is bound.
  23899. * @type {BABYLON.Observable}
  23900. */
  23901. this.onBindObservable = new BABYLON.Observable();
  23902. /**
  23903. * An event triggered when the material is unbound.
  23904. * @type {BABYLON.Observable}
  23905. */
  23906. this.onUnBindObservable = new BABYLON.Observable();
  23907. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23908. this.disableDepthWrite = false;
  23909. this._fogEnabled = true;
  23910. this.pointSize = 1.0;
  23911. this.zOffset = 0;
  23912. this._wasPreviouslyReady = false;
  23913. this._fillMode = Material.TriangleFillMode;
  23914. this.name = name;
  23915. this.id = name;
  23916. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23917. if (this._scene.useRightHandedSystem) {
  23918. this.sideOrientation = Material.ClockWiseSideOrientation;
  23919. }
  23920. else {
  23921. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23922. }
  23923. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23924. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23925. if (!doNotAdd) {
  23926. this._scene.materials.push(this);
  23927. }
  23928. }
  23929. Object.defineProperty(Material, "TriangleFillMode", {
  23930. get: function () {
  23931. return Material._TriangleFillMode;
  23932. },
  23933. enumerable: true,
  23934. configurable: true
  23935. });
  23936. Object.defineProperty(Material, "WireFrameFillMode", {
  23937. get: function () {
  23938. return Material._WireFrameFillMode;
  23939. },
  23940. enumerable: true,
  23941. configurable: true
  23942. });
  23943. Object.defineProperty(Material, "PointFillMode", {
  23944. get: function () {
  23945. return Material._PointFillMode;
  23946. },
  23947. enumerable: true,
  23948. configurable: true
  23949. });
  23950. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23951. get: function () {
  23952. return Material._ClockWiseSideOrientation;
  23953. },
  23954. enumerable: true,
  23955. configurable: true
  23956. });
  23957. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23958. get: function () {
  23959. return Material._CounterClockWiseSideOrientation;
  23960. },
  23961. enumerable: true,
  23962. configurable: true
  23963. });
  23964. Object.defineProperty(Material, "TextureDirtyFlag", {
  23965. get: function () {
  23966. return Material._TextureDirtyFlag;
  23967. },
  23968. enumerable: true,
  23969. configurable: true
  23970. });
  23971. Object.defineProperty(Material, "LightDirtyFlag", {
  23972. get: function () {
  23973. return Material._LightDirtyFlag;
  23974. },
  23975. enumerable: true,
  23976. configurable: true
  23977. });
  23978. Object.defineProperty(Material, "FresnelDirtyFlag", {
  23979. get: function () {
  23980. return Material._FresnelDirtyFlag;
  23981. },
  23982. enumerable: true,
  23983. configurable: true
  23984. });
  23985. Object.defineProperty(Material, "AttributesDirtyFlag", {
  23986. get: function () {
  23987. return Material._AttributesDirtyFlag;
  23988. },
  23989. enumerable: true,
  23990. configurable: true
  23991. });
  23992. Object.defineProperty(Material, "MiscDirtyFlag", {
  23993. get: function () {
  23994. return Material._MiscDirtyFlag;
  23995. },
  23996. enumerable: true,
  23997. configurable: true
  23998. });
  23999. Object.defineProperty(Material.prototype, "backFaceCulling", {
  24000. get: function () {
  24001. return this._backFaceCulling;
  24002. },
  24003. set: function (value) {
  24004. if (this._backFaceCulling === value) {
  24005. return;
  24006. }
  24007. this._backFaceCulling = value;
  24008. this.markAsDirty(Material.TextureDirtyFlag);
  24009. },
  24010. enumerable: true,
  24011. configurable: true
  24012. });
  24013. Object.defineProperty(Material.prototype, "onDispose", {
  24014. set: function (callback) {
  24015. if (this._onDisposeObserver) {
  24016. this.onDisposeObservable.remove(this._onDisposeObserver);
  24017. }
  24018. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24019. },
  24020. enumerable: true,
  24021. configurable: true
  24022. });
  24023. Object.defineProperty(Material.prototype, "onBind", {
  24024. set: function (callback) {
  24025. if (this._onBindObserver) {
  24026. this.onBindObservable.remove(this._onBindObserver);
  24027. }
  24028. this._onBindObserver = this.onBindObservable.add(callback);
  24029. },
  24030. enumerable: true,
  24031. configurable: true
  24032. });
  24033. Object.defineProperty(Material.prototype, "fogEnabled", {
  24034. get: function () {
  24035. return this._fogEnabled;
  24036. },
  24037. set: function (value) {
  24038. if (this._fogEnabled === value) {
  24039. return;
  24040. }
  24041. this._fogEnabled = value;
  24042. this.markAsDirty(Material.MiscDirtyFlag);
  24043. },
  24044. enumerable: true,
  24045. configurable: true
  24046. });
  24047. Object.defineProperty(Material.prototype, "wireframe", {
  24048. get: function () {
  24049. return this._fillMode === Material.WireFrameFillMode;
  24050. },
  24051. set: function (value) {
  24052. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24053. },
  24054. enumerable: true,
  24055. configurable: true
  24056. });
  24057. Object.defineProperty(Material.prototype, "pointsCloud", {
  24058. get: function () {
  24059. return this._fillMode === Material.PointFillMode;
  24060. },
  24061. set: function (value) {
  24062. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24063. },
  24064. enumerable: true,
  24065. configurable: true
  24066. });
  24067. Object.defineProperty(Material.prototype, "fillMode", {
  24068. get: function () {
  24069. return this._fillMode;
  24070. },
  24071. set: function (value) {
  24072. if (this._fillMode === value) {
  24073. return;
  24074. }
  24075. this._fillMode = value;
  24076. this.markAsDirty(Material.MiscDirtyFlag);
  24077. },
  24078. enumerable: true,
  24079. configurable: true
  24080. });
  24081. /**
  24082. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24083. * subclasses should override adding information pertainent to themselves
  24084. */
  24085. Material.prototype.toString = function (fullDetails) {
  24086. var ret = "Name: " + this.name;
  24087. if (fullDetails) {
  24088. }
  24089. return ret;
  24090. };
  24091. /**
  24092. * Child classes can use it to update shaders
  24093. */
  24094. Material.prototype.getClassName = function () {
  24095. return "Material";
  24096. };
  24097. Object.defineProperty(Material.prototype, "isFrozen", {
  24098. get: function () {
  24099. return this.checkReadyOnlyOnce;
  24100. },
  24101. enumerable: true,
  24102. configurable: true
  24103. });
  24104. Material.prototype.freeze = function () {
  24105. this.checkReadyOnlyOnce = true;
  24106. };
  24107. Material.prototype.unfreeze = function () {
  24108. this.checkReadyOnlyOnce = false;
  24109. };
  24110. Material.prototype.isReady = function (mesh, useInstances) {
  24111. return true;
  24112. };
  24113. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  24114. return false;
  24115. };
  24116. Material.prototype.getEffect = function () {
  24117. return this._effect;
  24118. };
  24119. Material.prototype.getScene = function () {
  24120. return this._scene;
  24121. };
  24122. Material.prototype.needAlphaBlending = function () {
  24123. return (this.alpha < 1.0);
  24124. };
  24125. Material.prototype.needAlphaTesting = function () {
  24126. return false;
  24127. };
  24128. Material.prototype.getAlphaTestTexture = function () {
  24129. return null;
  24130. };
  24131. Material.prototype.markDirty = function () {
  24132. this._wasPreviouslyReady = false;
  24133. };
  24134. Material.prototype._preBind = function (effect) {
  24135. var engine = this._scene.getEngine();
  24136. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  24137. engine.enableEffect(effect ? effect : this._effect);
  24138. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  24139. };
  24140. Material.prototype.bind = function (world, mesh) {
  24141. };
  24142. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  24143. };
  24144. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24145. };
  24146. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  24147. sceneUbo.bindToEffect(effect, "Scene");
  24148. };
  24149. Material.prototype.bindView = function (effect) {
  24150. if (!this._useUBO) {
  24151. effect.setMatrix("view", this.getScene().getViewMatrix());
  24152. }
  24153. else {
  24154. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24155. }
  24156. };
  24157. Material.prototype.bindViewProjection = function (effect) {
  24158. if (!this._useUBO) {
  24159. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24160. }
  24161. else {
  24162. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24163. }
  24164. };
  24165. Material.prototype._afterBind = function (mesh) {
  24166. this._scene._cachedMaterial = this;
  24167. this.onBindObservable.notifyObservers(mesh);
  24168. if (this.disableDepthWrite) {
  24169. var engine = this._scene.getEngine();
  24170. this._cachedDepthWriteState = engine.getDepthWrite();
  24171. engine.setDepthWrite(false);
  24172. }
  24173. };
  24174. Material.prototype.unbind = function () {
  24175. this.onUnBindObservable.notifyObservers(this);
  24176. if (this.disableDepthWrite) {
  24177. var engine = this._scene.getEngine();
  24178. engine.setDepthWrite(this._cachedDepthWriteState);
  24179. }
  24180. };
  24181. Material.prototype.getActiveTextures = function () {
  24182. return [];
  24183. };
  24184. Material.prototype.clone = function (name) {
  24185. return null;
  24186. };
  24187. Material.prototype.getBindedMeshes = function () {
  24188. var result = new Array();
  24189. for (var index = 0; index < this._scene.meshes.length; index++) {
  24190. var mesh = this._scene.meshes[index];
  24191. if (mesh.material === this) {
  24192. result.push(mesh);
  24193. }
  24194. }
  24195. return result;
  24196. };
  24197. // Force shader compilation including textures ready check
  24198. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  24199. var _this = this;
  24200. var subMesh = new BABYLON.BaseSubMesh();
  24201. var scene = this.getScene();
  24202. var engine = scene.getEngine();
  24203. var beforeRenderCallback = function () {
  24204. if (subMesh._materialDefines) {
  24205. subMesh._materialDefines._renderId = -1;
  24206. }
  24207. var alphaTestState = engine.getAlphaTesting();
  24208. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  24209. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  24210. scene.unregisterBeforeRender(beforeRenderCallback);
  24211. if (onCompiled) {
  24212. onCompiled(_this);
  24213. }
  24214. }
  24215. engine.setAlphaTesting(alphaTestState);
  24216. };
  24217. scene.registerBeforeRender(beforeRenderCallback);
  24218. };
  24219. Material.prototype.markAsDirty = function (flag) {
  24220. if (flag & Material.TextureDirtyFlag) {
  24221. this._markAllSubMeshesAsTexturesDirty();
  24222. }
  24223. if (flag & Material.LightDirtyFlag) {
  24224. this._markAllSubMeshesAsLightsDirty();
  24225. }
  24226. if (flag & Material.FresnelDirtyFlag) {
  24227. this._markAllSubMeshesAsFresnelDirty();
  24228. }
  24229. if (flag & Material.AttributesDirtyFlag) {
  24230. this._markAllSubMeshesAsAttributesDirty();
  24231. }
  24232. if (flag & Material.MiscDirtyFlag) {
  24233. this._markAllSubMeshesAsMiscDirty();
  24234. }
  24235. this.getScene().resetCachedMaterial();
  24236. };
  24237. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  24238. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24239. var mesh = _a[_i];
  24240. if (!mesh.subMeshes) {
  24241. continue;
  24242. }
  24243. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24244. var subMesh = _c[_b];
  24245. if (subMesh.getMaterial() !== this) {
  24246. continue;
  24247. }
  24248. if (!subMesh._materialDefines) {
  24249. return;
  24250. }
  24251. func(subMesh._materialDefines);
  24252. }
  24253. }
  24254. };
  24255. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  24256. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  24257. };
  24258. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24259. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24260. };
  24261. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24262. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24263. };
  24264. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  24265. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24266. };
  24267. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24268. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24269. };
  24270. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  24271. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24272. };
  24273. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24274. // Animations
  24275. this.getScene().stopAnimation(this);
  24276. // Remove from scene
  24277. var index = this._scene.materials.indexOf(this);
  24278. if (index >= 0) {
  24279. this._scene.materials.splice(index, 1);
  24280. }
  24281. // Remove from meshes
  24282. for (index = 0; index < this._scene.meshes.length; index++) {
  24283. var mesh = this._scene.meshes[index];
  24284. if (mesh.material === this) {
  24285. mesh.material = null;
  24286. if (mesh.geometry) {
  24287. var geometry = mesh.geometry;
  24288. if (this.storeEffectOnSubMeshes) {
  24289. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  24290. var subMesh = _a[_i];
  24291. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  24292. }
  24293. }
  24294. else {
  24295. geometry._releaseVertexArrayObject(this._effect);
  24296. }
  24297. }
  24298. }
  24299. }
  24300. this._uniformBuffer.dispose();
  24301. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24302. if (forceDisposeEffect && this._effect) {
  24303. if (this.storeEffectOnSubMeshes) {
  24304. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24305. var subMesh = _c[_b];
  24306. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  24307. }
  24308. }
  24309. else {
  24310. this._scene.getEngine()._releaseEffect(this._effect);
  24311. }
  24312. this._effect = null;
  24313. }
  24314. // Callback
  24315. this.onDisposeObservable.notifyObservers(this);
  24316. this.onDisposeObservable.clear();
  24317. this.onBindObservable.clear();
  24318. this.onUnBindObservable.clear();
  24319. };
  24320. Material.prototype.serialize = function () {
  24321. return BABYLON.SerializationHelper.Serialize(this);
  24322. };
  24323. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24324. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24325. multiMaterial.id = parsedMultiMaterial.id;
  24326. if (BABYLON.Tags) {
  24327. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24328. }
  24329. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24330. var subMatId = parsedMultiMaterial.materials[matIndex];
  24331. if (subMatId) {
  24332. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24333. }
  24334. else {
  24335. multiMaterial.subMaterials.push(null);
  24336. }
  24337. }
  24338. return multiMaterial;
  24339. };
  24340. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24341. if (!parsedMaterial.customType) {
  24342. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24343. }
  24344. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  24345. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  24346. if (!BABYLON.LegacyPBRMaterial) {
  24347. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24348. return;
  24349. }
  24350. }
  24351. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24352. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24353. ;
  24354. };
  24355. return Material;
  24356. }());
  24357. Material._TriangleFillMode = 0;
  24358. Material._WireFrameFillMode = 1;
  24359. Material._PointFillMode = 2;
  24360. Material._ClockWiseSideOrientation = 0;
  24361. Material._CounterClockWiseSideOrientation = 1;
  24362. Material._TextureDirtyFlag = 1;
  24363. Material._LightDirtyFlag = 2;
  24364. Material._FresnelDirtyFlag = 4;
  24365. Material._AttributesDirtyFlag = 8;
  24366. Material._MiscDirtyFlag = 16;
  24367. __decorate([
  24368. BABYLON.serialize()
  24369. ], Material.prototype, "id", void 0);
  24370. __decorate([
  24371. BABYLON.serialize()
  24372. ], Material.prototype, "name", void 0);
  24373. __decorate([
  24374. BABYLON.serialize()
  24375. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24376. __decorate([
  24377. BABYLON.serialize()
  24378. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24379. __decorate([
  24380. BABYLON.serialize()
  24381. ], Material.prototype, "state", void 0);
  24382. __decorate([
  24383. BABYLON.serialize()
  24384. ], Material.prototype, "alpha", void 0);
  24385. __decorate([
  24386. BABYLON.serialize("backFaceCulling")
  24387. ], Material.prototype, "_backFaceCulling", void 0);
  24388. __decorate([
  24389. BABYLON.serialize()
  24390. ], Material.prototype, "sideOrientation", void 0);
  24391. __decorate([
  24392. BABYLON.serialize()
  24393. ], Material.prototype, "alphaMode", void 0);
  24394. __decorate([
  24395. BABYLON.serialize()
  24396. ], Material.prototype, "disableDepthWrite", void 0);
  24397. __decorate([
  24398. BABYLON.serialize("fogEnabled")
  24399. ], Material.prototype, "_fogEnabled", void 0);
  24400. __decorate([
  24401. BABYLON.serialize()
  24402. ], Material.prototype, "pointSize", void 0);
  24403. __decorate([
  24404. BABYLON.serialize()
  24405. ], Material.prototype, "zOffset", void 0);
  24406. __decorate([
  24407. BABYLON.serialize()
  24408. ], Material.prototype, "wireframe", null);
  24409. __decorate([
  24410. BABYLON.serialize()
  24411. ], Material.prototype, "pointsCloud", null);
  24412. __decorate([
  24413. BABYLON.serialize()
  24414. ], Material.prototype, "fillMode", null);
  24415. BABYLON.Material = Material;
  24416. })(BABYLON || (BABYLON = {}));
  24417. //# sourceMappingURL=babylon.material.js.map
  24418. var BABYLON;
  24419. (function (BABYLON) {
  24420. var UniformBuffer = (function () {
  24421. /**
  24422. * Uniform buffer objects.
  24423. *
  24424. * Handles blocks of uniform on the GPU.
  24425. *
  24426. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24427. *
  24428. * For more information, please refer to :
  24429. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24430. */
  24431. function UniformBuffer(engine, data, dynamic) {
  24432. this._engine = engine;
  24433. this._noUBO = engine.webGLVersion === 1;
  24434. this._dynamic = dynamic;
  24435. this._data = data || [];
  24436. this._uniformLocations = {};
  24437. this._uniformSizes = {};
  24438. this._uniformLocationPointer = 0;
  24439. this._needSync = false;
  24440. if (this._noUBO) {
  24441. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24442. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24443. this.updateFloat = this._updateFloatForEffect;
  24444. this.updateFloat2 = this._updateFloat2ForEffect;
  24445. this.updateFloat3 = this._updateFloat3ForEffect;
  24446. this.updateFloat4 = this._updateFloat4ForEffect;
  24447. this.updateMatrix = this._updateMatrixForEffect;
  24448. this.updateVector3 = this._updateVector3ForEffect;
  24449. this.updateVector4 = this._updateVector4ForEffect;
  24450. this.updateColor3 = this._updateColor3ForEffect;
  24451. this.updateColor4 = this._updateColor4ForEffect;
  24452. }
  24453. else {
  24454. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24455. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24456. this.updateFloat = this._updateFloatForUniform;
  24457. this.updateFloat2 = this._updateFloat2ForUniform;
  24458. this.updateFloat3 = this._updateFloat3ForUniform;
  24459. this.updateFloat4 = this._updateFloat4ForUniform;
  24460. this.updateMatrix = this._updateMatrixForUniform;
  24461. this.updateVector3 = this._updateVector3ForUniform;
  24462. this.updateVector4 = this._updateVector4ForUniform;
  24463. this.updateColor3 = this._updateColor3ForUniform;
  24464. this.updateColor4 = this._updateColor4ForUniform;
  24465. }
  24466. }
  24467. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24468. // Properties
  24469. /**
  24470. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24471. * or just falling back on setUniformXXX calls.
  24472. */
  24473. get: function () {
  24474. return !this._noUBO;
  24475. },
  24476. enumerable: true,
  24477. configurable: true
  24478. });
  24479. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24480. /**
  24481. * Indicates if the WebGL underlying uniform buffer is in sync
  24482. * with the javascript cache data.
  24483. */
  24484. get: function () {
  24485. return !this._needSync;
  24486. },
  24487. enumerable: true,
  24488. configurable: true
  24489. });
  24490. /**
  24491. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24492. * Also, a dynamic UniformBuffer will disable cache verification and always
  24493. * update the underlying WebGL uniform buffer to the GPU.
  24494. */
  24495. UniformBuffer.prototype.isDynamic = function () {
  24496. return this._dynamic;
  24497. };
  24498. /**
  24499. * The data cache on JS side.
  24500. */
  24501. UniformBuffer.prototype.getData = function () {
  24502. return this._bufferData;
  24503. };
  24504. /**
  24505. * The underlying WebGL Uniform buffer.
  24506. */
  24507. UniformBuffer.prototype.getBuffer = function () {
  24508. return this._buffer;
  24509. };
  24510. /**
  24511. * std140 layout specifies how to align data within an UBO structure.
  24512. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24513. * for specs.
  24514. */
  24515. UniformBuffer.prototype._fillAlignment = function (size) {
  24516. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24517. // and 4x4 matrices
  24518. // TODO : change if other types are used
  24519. var alignment;
  24520. if (size <= 2) {
  24521. alignment = size;
  24522. }
  24523. else {
  24524. alignment = 4;
  24525. }
  24526. if ((this._uniformLocationPointer % alignment) !== 0) {
  24527. var oldPointer = this._uniformLocationPointer;
  24528. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24529. var diff = this._uniformLocationPointer - oldPointer;
  24530. for (var i = 0; i < diff; i++) {
  24531. this._data.push(0);
  24532. }
  24533. }
  24534. };
  24535. /**
  24536. * Adds an uniform in the buffer.
  24537. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24538. * for the layout to be correct !
  24539. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24540. * @param {number|number[]} size Data size, or data directly.
  24541. */
  24542. UniformBuffer.prototype.addUniform = function (name, size) {
  24543. if (this._noUBO) {
  24544. return;
  24545. }
  24546. if (this._uniformLocations[name] !== undefined) {
  24547. // Already existing uniform
  24548. return;
  24549. }
  24550. // This function must be called in the order of the shader layout !
  24551. // size can be the size of the uniform, or data directly
  24552. var data;
  24553. if (size instanceof Array) {
  24554. data = size;
  24555. size = data.length;
  24556. }
  24557. else {
  24558. size = size;
  24559. data = [];
  24560. // Fill with zeros
  24561. for (var i = 0; i < size; i++) {
  24562. data.push(0);
  24563. }
  24564. }
  24565. this._fillAlignment(size);
  24566. this._uniformSizes[name] = size;
  24567. this._uniformLocations[name] = this._uniformLocationPointer;
  24568. this._uniformLocationPointer += size;
  24569. for (var i = 0; i < size; i++) {
  24570. this._data.push(data[i]);
  24571. }
  24572. this._needSync = true;
  24573. };
  24574. /**
  24575. * Wrapper for addUniform.
  24576. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24577. * @param {Matrix} mat A 4x4 matrix.
  24578. */
  24579. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24580. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24581. };
  24582. /**
  24583. * Wrapper for addUniform.
  24584. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24585. * @param {number} x
  24586. * @param {number} y
  24587. */
  24588. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24589. var temp = [x, y];
  24590. this.addUniform(name, temp);
  24591. };
  24592. /**
  24593. * Wrapper for addUniform.
  24594. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24595. * @param {number} x
  24596. * @param {number} y
  24597. * @param {number} z
  24598. */
  24599. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24600. var temp = [x, y, z];
  24601. this.addUniform(name, temp);
  24602. };
  24603. /**
  24604. * Wrapper for addUniform.
  24605. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24606. * @param {Color3} color
  24607. */
  24608. UniformBuffer.prototype.addColor3 = function (name, color) {
  24609. var temp = [];
  24610. color.toArray(temp);
  24611. this.addUniform(name, temp);
  24612. };
  24613. /**
  24614. * Wrapper for addUniform.
  24615. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24616. * @param {Color3} color
  24617. * @param {number} alpha
  24618. */
  24619. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24620. var temp = [];
  24621. color.toArray(temp);
  24622. temp.push(alpha);
  24623. this.addUniform(name, temp);
  24624. };
  24625. /**
  24626. * Wrapper for addUniform.
  24627. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24628. * @param {Vector3} vector
  24629. */
  24630. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24631. var temp = [];
  24632. vector.toArray(temp);
  24633. this.addUniform(name, temp);
  24634. };
  24635. /**
  24636. * Wrapper for addUniform.
  24637. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24638. */
  24639. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24640. this.addUniform(name, 12);
  24641. };
  24642. /**
  24643. * Wrapper for addUniform.
  24644. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24645. */
  24646. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24647. this.addUniform(name, 8);
  24648. };
  24649. /**
  24650. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24651. */
  24652. UniformBuffer.prototype.create = function () {
  24653. if (this._noUBO) {
  24654. return;
  24655. }
  24656. if (this._buffer) {
  24657. return; // nothing to do
  24658. }
  24659. // See spec, alignment must be filled as a vec4
  24660. this._fillAlignment(4);
  24661. this._bufferData = new Float32Array(this._data);
  24662. if (this._dynamic) {
  24663. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24664. }
  24665. else {
  24666. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24667. }
  24668. this._needSync = true;
  24669. };
  24670. /**
  24671. * Updates the WebGL Uniform Buffer on the GPU.
  24672. * If the `dynamic` flag is set to true, no cache comparison is done.
  24673. * Otherwise, the buffer will be updated only if the cache differs.
  24674. */
  24675. UniformBuffer.prototype.update = function () {
  24676. if (!this._buffer) {
  24677. this.create();
  24678. return;
  24679. }
  24680. if (!this._dynamic && !this._needSync) {
  24681. return;
  24682. }
  24683. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24684. this._needSync = false;
  24685. };
  24686. /**
  24687. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24688. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24689. * @param {number[]|Float32Array} data Flattened data
  24690. * @param {number} size Size of the data.
  24691. */
  24692. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24693. var location = this._uniformLocations[uniformName];
  24694. if (location === undefined) {
  24695. if (this._buffer) {
  24696. // Cannot add an uniform if the buffer is already created
  24697. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24698. return;
  24699. }
  24700. this.addUniform(uniformName, size);
  24701. location = this._uniformLocations[uniformName];
  24702. }
  24703. if (!this._buffer) {
  24704. this.create();
  24705. }
  24706. if (!this._dynamic) {
  24707. // Cache for static uniform buffers
  24708. var changed = false;
  24709. for (var i = 0; i < size; i++) {
  24710. if (this._bufferData[location + i] !== data[i]) {
  24711. changed = true;
  24712. this._bufferData[location + i] = data[i];
  24713. }
  24714. }
  24715. this._needSync = this._needSync || changed;
  24716. }
  24717. else {
  24718. // No cache for dynamic
  24719. for (var i = 0; i < size; i++) {
  24720. this._bufferData[location + i] = data[i];
  24721. }
  24722. }
  24723. };
  24724. // Update methods
  24725. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24726. // To match std140, matrix must be realigned
  24727. for (var i = 0; i < 3; i++) {
  24728. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24729. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24730. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24731. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24732. }
  24733. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24734. };
  24735. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24736. this._currentEffect.setMatrix3x3(name, matrix);
  24737. };
  24738. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24739. this._currentEffect.setMatrix2x2(name, matrix);
  24740. };
  24741. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24742. // To match std140, matrix must be realigned
  24743. for (var i = 0; i < 2; i++) {
  24744. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24745. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24746. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24747. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24748. }
  24749. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24750. };
  24751. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24752. this._currentEffect.setFloat(name, x);
  24753. };
  24754. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24755. UniformBuffer._tempBuffer[0] = x;
  24756. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24757. };
  24758. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  24759. if (suffix === void 0) { suffix = ""; }
  24760. this._currentEffect.setFloat2(name + suffix, x, y);
  24761. };
  24762. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  24763. if (suffix === void 0) { suffix = ""; }
  24764. UniformBuffer._tempBuffer[0] = x;
  24765. UniformBuffer._tempBuffer[1] = y;
  24766. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24767. };
  24768. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24769. if (suffix === void 0) { suffix = ""; }
  24770. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24771. };
  24772. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24773. if (suffix === void 0) { suffix = ""; }
  24774. UniformBuffer._tempBuffer[0] = x;
  24775. UniformBuffer._tempBuffer[1] = y;
  24776. UniformBuffer._tempBuffer[2] = z;
  24777. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24778. };
  24779. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24780. if (suffix === void 0) { suffix = ""; }
  24781. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24782. };
  24783. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24784. if (suffix === void 0) { suffix = ""; }
  24785. UniformBuffer._tempBuffer[0] = x;
  24786. UniformBuffer._tempBuffer[1] = y;
  24787. UniformBuffer._tempBuffer[2] = z;
  24788. UniformBuffer._tempBuffer[3] = w;
  24789. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24790. };
  24791. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24792. this._currentEffect.setMatrix(name, mat);
  24793. };
  24794. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24795. this.updateUniform(name, mat.toArray(), 16);
  24796. };
  24797. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24798. this._currentEffect.setVector3(name, vector);
  24799. };
  24800. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24801. vector.toArray(UniformBuffer._tempBuffer);
  24802. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24803. };
  24804. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24805. this._currentEffect.setVector4(name, vector);
  24806. };
  24807. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24808. vector.toArray(UniformBuffer._tempBuffer);
  24809. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24810. };
  24811. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24812. if (suffix === void 0) { suffix = ""; }
  24813. this._currentEffect.setColor3(name + suffix, color);
  24814. };
  24815. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24816. if (suffix === void 0) { suffix = ""; }
  24817. color.toArray(UniformBuffer._tempBuffer);
  24818. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24819. };
  24820. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24821. if (suffix === void 0) { suffix = ""; }
  24822. this._currentEffect.setColor4(name + suffix, color, alpha);
  24823. };
  24824. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24825. if (suffix === void 0) { suffix = ""; }
  24826. color.toArray(UniformBuffer._tempBuffer);
  24827. UniformBuffer._tempBuffer[3] = alpha;
  24828. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24829. };
  24830. /**
  24831. * Sets a sampler uniform on the effect.
  24832. * @param {string} name Name of the sampler.
  24833. * @param {Texture} texture
  24834. */
  24835. UniformBuffer.prototype.setTexture = function (name, texture) {
  24836. this._currentEffect.setTexture(name, texture);
  24837. };
  24838. /**
  24839. * Directly updates the value of the uniform in the cache AND on the GPU.
  24840. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24841. * @param {number[]|Float32Array} data Flattened data
  24842. */
  24843. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24844. this.updateUniform(uniformName, data, data.length);
  24845. this.update();
  24846. };
  24847. /**
  24848. * Binds this uniform buffer to an effect.
  24849. * @param {Effect} effect
  24850. * @param {string} name Name of the uniform block in the shader.
  24851. */
  24852. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24853. this._currentEffect = effect;
  24854. if (this._noUBO) {
  24855. return;
  24856. }
  24857. effect.bindUniformBuffer(this._buffer, name);
  24858. };
  24859. /**
  24860. * Disposes the uniform buffer.
  24861. */
  24862. UniformBuffer.prototype.dispose = function () {
  24863. if (!this._buffer) {
  24864. return;
  24865. }
  24866. if (this._engine._releaseBuffer(this._buffer)) {
  24867. this._buffer = null;
  24868. }
  24869. };
  24870. return UniformBuffer;
  24871. }());
  24872. // Pool for avoiding memory leaks
  24873. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24874. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24875. BABYLON.UniformBuffer = UniformBuffer;
  24876. })(BABYLON || (BABYLON = {}));
  24877. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24878. var BABYLON;
  24879. (function (BABYLON) {
  24880. var PushMaterial = (function (_super) {
  24881. __extends(PushMaterial, _super);
  24882. function PushMaterial(name, scene) {
  24883. var _this = _super.call(this, name, scene) || this;
  24884. _this.storeEffectOnSubMeshes = true;
  24885. return _this;
  24886. }
  24887. PushMaterial.prototype.getEffect = function () {
  24888. return this._activeEffect;
  24889. };
  24890. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24891. if (!mesh) {
  24892. return false;
  24893. }
  24894. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24895. return true;
  24896. }
  24897. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24898. };
  24899. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24900. this._activeEffect.setMatrix("world", world);
  24901. };
  24902. PushMaterial.prototype.bind = function (world, mesh) {
  24903. if (!mesh) {
  24904. return;
  24905. }
  24906. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24907. };
  24908. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24909. _super.prototype._afterBind.call(this, mesh);
  24910. this.getScene()._cachedEffect = effect;
  24911. };
  24912. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24913. if (visibility === void 0) { visibility = 0; }
  24914. return scene.isCachedMaterialValid(this, effect, visibility);
  24915. };
  24916. return PushMaterial;
  24917. }(BABYLON.Material));
  24918. BABYLON.PushMaterial = PushMaterial;
  24919. })(BABYLON || (BABYLON = {}));
  24920. //# sourceMappingURL=babylon.pushMaterial.js.map
  24921. var BABYLON;
  24922. (function (BABYLON) {
  24923. var VertexData = (function () {
  24924. function VertexData() {
  24925. }
  24926. VertexData.prototype.set = function (data, kind) {
  24927. switch (kind) {
  24928. case BABYLON.VertexBuffer.PositionKind:
  24929. this.positions = data;
  24930. break;
  24931. case BABYLON.VertexBuffer.NormalKind:
  24932. this.normals = data;
  24933. break;
  24934. case BABYLON.VertexBuffer.TangentKind:
  24935. this.tangents = data;
  24936. break;
  24937. case BABYLON.VertexBuffer.UVKind:
  24938. this.uvs = data;
  24939. break;
  24940. case BABYLON.VertexBuffer.UV2Kind:
  24941. this.uvs2 = data;
  24942. break;
  24943. case BABYLON.VertexBuffer.UV3Kind:
  24944. this.uvs3 = data;
  24945. break;
  24946. case BABYLON.VertexBuffer.UV4Kind:
  24947. this.uvs4 = data;
  24948. break;
  24949. case BABYLON.VertexBuffer.UV5Kind:
  24950. this.uvs5 = data;
  24951. break;
  24952. case BABYLON.VertexBuffer.UV6Kind:
  24953. this.uvs6 = data;
  24954. break;
  24955. case BABYLON.VertexBuffer.ColorKind:
  24956. this.colors = data;
  24957. break;
  24958. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24959. this.matricesIndices = data;
  24960. break;
  24961. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24962. this.matricesWeights = data;
  24963. break;
  24964. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24965. this.matricesIndicesExtra = data;
  24966. break;
  24967. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24968. this.matricesWeightsExtra = data;
  24969. break;
  24970. }
  24971. };
  24972. /**
  24973. * Associates the vertexData to the passed Mesh.
  24974. * Sets it as updatable or not (default `false`).
  24975. * Returns the VertexData.
  24976. */
  24977. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24978. this._applyTo(mesh, updatable);
  24979. return this;
  24980. };
  24981. /**
  24982. * Associates the vertexData to the passed Geometry.
  24983. * Sets it as updatable or not (default `false`).
  24984. * Returns the VertexData.
  24985. */
  24986. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24987. this._applyTo(geometry, updatable);
  24988. return this;
  24989. };
  24990. /**
  24991. * Updates the associated mesh.
  24992. * Returns the VertexData.
  24993. */
  24994. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24995. this._update(mesh);
  24996. return this;
  24997. };
  24998. /**
  24999. * Updates the associated geometry.
  25000. * Returns the VertexData.
  25001. */
  25002. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25003. this._update(geometry);
  25004. return this;
  25005. };
  25006. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25007. if (this.positions) {
  25008. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25009. }
  25010. if (this.normals) {
  25011. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25012. }
  25013. if (this.tangents) {
  25014. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  25015. }
  25016. if (this.uvs) {
  25017. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25018. }
  25019. if (this.uvs2) {
  25020. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25021. }
  25022. if (this.uvs3) {
  25023. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25024. }
  25025. if (this.uvs4) {
  25026. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25027. }
  25028. if (this.uvs5) {
  25029. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25030. }
  25031. if (this.uvs6) {
  25032. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25033. }
  25034. if (this.colors) {
  25035. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25036. }
  25037. if (this.matricesIndices) {
  25038. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25039. }
  25040. if (this.matricesWeights) {
  25041. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25042. }
  25043. if (this.matricesIndicesExtra) {
  25044. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  25045. }
  25046. if (this.matricesWeightsExtra) {
  25047. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  25048. }
  25049. if (this.indices) {
  25050. meshOrGeometry.setIndices(this.indices);
  25051. }
  25052. return this;
  25053. };
  25054. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25055. if (this.positions) {
  25056. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25057. }
  25058. if (this.normals) {
  25059. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25060. }
  25061. if (this.tangents) {
  25062. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  25063. }
  25064. if (this.uvs) {
  25065. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25066. }
  25067. if (this.uvs2) {
  25068. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25069. }
  25070. if (this.uvs3) {
  25071. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25072. }
  25073. if (this.uvs4) {
  25074. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25075. }
  25076. if (this.uvs5) {
  25077. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25078. }
  25079. if (this.uvs6) {
  25080. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25081. }
  25082. if (this.colors) {
  25083. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25084. }
  25085. if (this.matricesIndices) {
  25086. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25087. }
  25088. if (this.matricesWeights) {
  25089. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25090. }
  25091. if (this.matricesIndicesExtra) {
  25092. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  25093. }
  25094. if (this.matricesWeightsExtra) {
  25095. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  25096. }
  25097. if (this.indices) {
  25098. meshOrGeometry.setIndices(this.indices);
  25099. }
  25100. return this;
  25101. };
  25102. /**
  25103. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  25104. * Returns the VertexData.
  25105. */
  25106. VertexData.prototype.transform = function (matrix) {
  25107. var transformed = BABYLON.Vector3.Zero();
  25108. var index;
  25109. if (this.positions) {
  25110. var position = BABYLON.Vector3.Zero();
  25111. for (index = 0; index < this.positions.length; index += 3) {
  25112. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25113. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25114. this.positions[index] = transformed.x;
  25115. this.positions[index + 1] = transformed.y;
  25116. this.positions[index + 2] = transformed.z;
  25117. }
  25118. }
  25119. if (this.normals) {
  25120. var normal = BABYLON.Vector3.Zero();
  25121. for (index = 0; index < this.normals.length; index += 3) {
  25122. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25123. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25124. this.normals[index] = transformed.x;
  25125. this.normals[index + 1] = transformed.y;
  25126. this.normals[index + 2] = transformed.z;
  25127. }
  25128. }
  25129. if (this.tangents) {
  25130. var tangent = BABYLON.Vector4.Zero();
  25131. var tangentTransformed = BABYLON.Vector4.Zero();
  25132. for (index = 0; index < this.tangents.length; index += 4) {
  25133. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  25134. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  25135. this.tangents[index] = tangentTransformed.x;
  25136. this.tangents[index + 1] = tangentTransformed.y;
  25137. this.tangents[index + 2] = tangentTransformed.z;
  25138. this.tangents[index + 3] = tangentTransformed.w;
  25139. }
  25140. }
  25141. return this;
  25142. };
  25143. /**
  25144. * Merges the passed VertexData into the current one.
  25145. * Returns the modified VertexData.
  25146. */
  25147. VertexData.prototype.merge = function (other) {
  25148. if (other.indices) {
  25149. if (!this.indices) {
  25150. this.indices = [];
  25151. }
  25152. var offset = this.positions ? this.positions.length / 3 : 0;
  25153. for (var index = 0; index < other.indices.length; index++) {
  25154. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  25155. this.indices.push(other.indices[index] + offset);
  25156. }
  25157. }
  25158. this.positions = this._mergeElement(this.positions, other.positions);
  25159. this.normals = this._mergeElement(this.normals, other.normals);
  25160. this.tangents = this._mergeElement(this.tangents, other.tangents);
  25161. this.uvs = this._mergeElement(this.uvs, other.uvs);
  25162. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  25163. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  25164. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  25165. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  25166. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  25167. this.colors = this._mergeElement(this.colors, other.colors);
  25168. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  25169. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  25170. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  25171. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  25172. return this;
  25173. };
  25174. VertexData.prototype._mergeElement = function (source, other) {
  25175. if (!other)
  25176. return source;
  25177. if (!source)
  25178. return other;
  25179. var len = other.length + source.length;
  25180. var isSrcTypedArray = source instanceof Float32Array;
  25181. var isOthTypedArray = other instanceof Float32Array;
  25182. // use non-loop method when the source is Float32Array
  25183. if (isSrcTypedArray) {
  25184. var ret32 = new Float32Array(len);
  25185. ret32.set(source);
  25186. ret32.set(other, source.length);
  25187. return ret32;
  25188. // source is number[], when other is also use concat
  25189. }
  25190. else if (!isOthTypedArray) {
  25191. return source.concat(other);
  25192. // source is a number[], but other is a Float32Array, loop required
  25193. }
  25194. else {
  25195. var ret = source.slice(0); // copy source to a separate array
  25196. for (var i = 0, len = other.length; i < len; i++) {
  25197. ret.push(other[i]);
  25198. }
  25199. return ret;
  25200. }
  25201. };
  25202. /**
  25203. * Serializes the VertexData.
  25204. * Returns a serialized object.
  25205. */
  25206. VertexData.prototype.serialize = function () {
  25207. var serializationObject = this.serialize();
  25208. if (this.positions) {
  25209. serializationObject.positions = this.positions;
  25210. }
  25211. if (this.normals) {
  25212. serializationObject.normals = this.normals;
  25213. }
  25214. if (this.tangents) {
  25215. serializationObject.tangents = this.tangents;
  25216. }
  25217. if (this.uvs) {
  25218. serializationObject.uvs = this.uvs;
  25219. }
  25220. if (this.uvs2) {
  25221. serializationObject.uvs2 = this.uvs2;
  25222. }
  25223. if (this.uvs3) {
  25224. serializationObject.uvs3 = this.uvs3;
  25225. }
  25226. if (this.uvs4) {
  25227. serializationObject.uvs4 = this.uvs4;
  25228. }
  25229. if (this.uvs5) {
  25230. serializationObject.uvs5 = this.uvs5;
  25231. }
  25232. if (this.uvs6) {
  25233. serializationObject.uvs6 = this.uvs6;
  25234. }
  25235. if (this.colors) {
  25236. serializationObject.colors = this.colors;
  25237. }
  25238. if (this.matricesIndices) {
  25239. serializationObject.matricesIndices = this.matricesIndices;
  25240. serializationObject.matricesIndices._isExpanded = true;
  25241. }
  25242. if (this.matricesWeights) {
  25243. serializationObject.matricesWeights = this.matricesWeights;
  25244. }
  25245. if (this.matricesIndicesExtra) {
  25246. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  25247. serializationObject.matricesIndicesExtra._isExpanded = true;
  25248. }
  25249. if (this.matricesWeightsExtra) {
  25250. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  25251. }
  25252. serializationObject.indices = this.indices;
  25253. return serializationObject;
  25254. };
  25255. // Statics
  25256. /**
  25257. * Returns the object VertexData associated to the passed mesh.
  25258. */
  25259. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  25260. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  25261. };
  25262. /**
  25263. * Returns the object VertexData associated to the passed geometry.
  25264. */
  25265. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  25266. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  25267. };
  25268. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  25269. var result = new VertexData();
  25270. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25271. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  25272. }
  25273. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25274. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25275. }
  25276. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25277. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25278. }
  25279. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25280. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25281. }
  25282. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25283. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25284. }
  25285. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25286. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25287. }
  25288. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25289. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25290. }
  25291. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25292. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25293. }
  25294. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25295. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25296. }
  25297. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25298. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25299. }
  25300. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25301. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25302. }
  25303. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25304. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25305. }
  25306. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25307. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25308. }
  25309. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25310. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25311. }
  25312. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25313. return result;
  25314. };
  25315. /**
  25316. * Creates the vertexData of the Ribbon.
  25317. */
  25318. VertexData.CreateRibbon = function (options) {
  25319. var pathArray = options.pathArray;
  25320. var closeArray = options.closeArray || false;
  25321. var closePath = options.closePath || false;
  25322. var invertUV = options.invertUV || false;
  25323. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25324. var offset = options.offset || defaultOffset;
  25325. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25326. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25327. var customUV = options.uvs;
  25328. var customColors = options.colors;
  25329. var positions = [];
  25330. var indices = [];
  25331. var normals = [];
  25332. var uvs = [];
  25333. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25334. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25335. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25336. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25337. var minlg; // minimal length among all paths from pathArray
  25338. var lg = []; // array of path lengths : nb of vertex per path
  25339. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25340. var p; // path iterator
  25341. var i; // point iterator
  25342. var j; // point iterator
  25343. // if single path in pathArray
  25344. if (pathArray.length < 2) {
  25345. var ar1 = [];
  25346. var ar2 = [];
  25347. for (i = 0; i < pathArray[0].length - offset; i++) {
  25348. ar1.push(pathArray[0][i]);
  25349. ar2.push(pathArray[0][i + offset]);
  25350. }
  25351. pathArray = [ar1, ar2];
  25352. }
  25353. // positions and horizontal distances (u)
  25354. var idc = 0;
  25355. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25356. var path;
  25357. var l;
  25358. minlg = pathArray[0].length;
  25359. var vectlg;
  25360. var dist;
  25361. for (p = 0; p < pathArray.length; p++) {
  25362. uTotalDistance[p] = 0;
  25363. us[p] = [0];
  25364. path = pathArray[p];
  25365. l = path.length;
  25366. minlg = (minlg < l) ? minlg : l;
  25367. j = 0;
  25368. while (j < l) {
  25369. positions.push(path[j].x, path[j].y, path[j].z);
  25370. if (j > 0) {
  25371. vectlg = path[j].subtract(path[j - 1]).length();
  25372. dist = vectlg + uTotalDistance[p];
  25373. us[p].push(dist);
  25374. uTotalDistance[p] = dist;
  25375. }
  25376. j++;
  25377. }
  25378. if (closePath) {
  25379. j--;
  25380. positions.push(path[0].x, path[0].y, path[0].z);
  25381. vectlg = path[j].subtract(path[0]).length();
  25382. dist = vectlg + uTotalDistance[p];
  25383. us[p].push(dist);
  25384. uTotalDistance[p] = dist;
  25385. }
  25386. lg[p] = l + closePathCorr;
  25387. idx[p] = idc;
  25388. idc += (l + closePathCorr);
  25389. }
  25390. // vertical distances (v)
  25391. var path1;
  25392. var path2;
  25393. var vertex1;
  25394. var vertex2;
  25395. for (i = 0; i < minlg + closePathCorr; i++) {
  25396. vTotalDistance[i] = 0;
  25397. vs[i] = [0];
  25398. for (p = 0; p < pathArray.length - 1; p++) {
  25399. path1 = pathArray[p];
  25400. path2 = pathArray[p + 1];
  25401. if (i === minlg) {
  25402. vertex1 = path1[0];
  25403. vertex2 = path2[0];
  25404. }
  25405. else {
  25406. vertex1 = path1[i];
  25407. vertex2 = path2[i];
  25408. }
  25409. vectlg = vertex2.subtract(vertex1).length();
  25410. dist = vectlg + vTotalDistance[i];
  25411. vs[i].push(dist);
  25412. vTotalDistance[i] = dist;
  25413. }
  25414. if (closeArray) {
  25415. path1 = pathArray[p];
  25416. path2 = pathArray[0];
  25417. if (i === minlg) {
  25418. vertex2 = path2[0];
  25419. }
  25420. vectlg = vertex2.subtract(vertex1).length();
  25421. dist = vectlg + vTotalDistance[i];
  25422. vTotalDistance[i] = dist;
  25423. }
  25424. }
  25425. // uvs
  25426. var u;
  25427. var v;
  25428. if (customUV) {
  25429. for (p = 0; p < customUV.length; p++) {
  25430. uvs.push(customUV[p].x, customUV[p].y);
  25431. }
  25432. }
  25433. else {
  25434. for (p = 0; p < pathArray.length; p++) {
  25435. for (i = 0; i < minlg + closePathCorr; i++) {
  25436. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25437. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25438. if (invertUV) {
  25439. uvs.push(v, u);
  25440. }
  25441. else {
  25442. uvs.push(u, v);
  25443. }
  25444. }
  25445. }
  25446. }
  25447. // indices
  25448. p = 0; // path index
  25449. var pi = 0; // positions array index
  25450. var l1 = lg[p] - 1; // path1 length
  25451. var l2 = lg[p + 1] - 1; // path2 length
  25452. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25453. var shft = idx[1] - idx[0]; // shift
  25454. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25455. while (pi <= min && p < path1nb) {
  25456. // 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
  25457. indices.push(pi, pi + shft, pi + 1);
  25458. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25459. pi += 1;
  25460. if (pi === min) {
  25461. p++;
  25462. if (p === lg.length - 1) {
  25463. shft = idx[0] - idx[p];
  25464. l1 = lg[p] - 1;
  25465. l2 = lg[0] - 1;
  25466. }
  25467. else {
  25468. shft = idx[p + 1] - idx[p];
  25469. l1 = lg[p] - 1;
  25470. l2 = lg[p + 1] - 1;
  25471. }
  25472. pi = idx[p];
  25473. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25474. }
  25475. }
  25476. // normals
  25477. VertexData.ComputeNormals(positions, indices, normals);
  25478. if (closePath) {
  25479. var indexFirst = 0;
  25480. var indexLast = 0;
  25481. for (p = 0; p < pathArray.length; p++) {
  25482. indexFirst = idx[p] * 3;
  25483. if (p + 1 < pathArray.length) {
  25484. indexLast = (idx[p + 1] - 1) * 3;
  25485. }
  25486. else {
  25487. indexLast = normals.length - 3;
  25488. }
  25489. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25490. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25491. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25492. normals[indexLast] = normals[indexFirst];
  25493. normals[indexLast + 1] = normals[indexFirst + 1];
  25494. normals[indexLast + 2] = normals[indexFirst + 2];
  25495. }
  25496. }
  25497. // sides
  25498. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25499. // Colors
  25500. if (customColors) {
  25501. var colors = new Float32Array(customColors.length * 4);
  25502. for (var c = 0; c < customColors.length; c++) {
  25503. colors[c * 4] = customColors[c].r;
  25504. colors[c * 4 + 1] = customColors[c].g;
  25505. colors[c * 4 + 2] = customColors[c].b;
  25506. colors[c * 4 + 3] = customColors[c].a;
  25507. }
  25508. }
  25509. // Result
  25510. var vertexData = new VertexData();
  25511. var positions32 = new Float32Array(positions);
  25512. var normals32 = new Float32Array(normals);
  25513. var uvs32 = new Float32Array(uvs);
  25514. vertexData.indices = indices;
  25515. vertexData.positions = positions32;
  25516. vertexData.normals = normals32;
  25517. vertexData.uvs = uvs32;
  25518. if (customColors) {
  25519. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25520. }
  25521. if (closePath) {
  25522. vertexData._idx = idx;
  25523. }
  25524. return vertexData;
  25525. };
  25526. /**
  25527. * Creates the VertexData of the Box.
  25528. */
  25529. VertexData.CreateBox = function (options) {
  25530. var normalsSource = [
  25531. new BABYLON.Vector3(0, 0, 1),
  25532. new BABYLON.Vector3(0, 0, -1),
  25533. new BABYLON.Vector3(1, 0, 0),
  25534. new BABYLON.Vector3(-1, 0, 0),
  25535. new BABYLON.Vector3(0, 1, 0),
  25536. new BABYLON.Vector3(0, -1, 0)
  25537. ];
  25538. var indices = [];
  25539. var positions = [];
  25540. var normals = [];
  25541. var uvs = [];
  25542. var width = options.width || options.size || 1;
  25543. var height = options.height || options.size || 1;
  25544. var depth = options.depth || options.size || 1;
  25545. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25546. var faceUV = options.faceUV || new Array(6);
  25547. var faceColors = options.faceColors;
  25548. var colors = [];
  25549. // default face colors and UV if undefined
  25550. for (var f = 0; f < 6; f++) {
  25551. if (faceUV[f] === undefined) {
  25552. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25553. }
  25554. if (faceColors && faceColors[f] === undefined) {
  25555. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25556. }
  25557. }
  25558. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25559. // Create each face in turn.
  25560. for (var index = 0; index < normalsSource.length; index++) {
  25561. var normal = normalsSource[index];
  25562. // Get two vectors perpendicular to the face normal and to each other.
  25563. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25564. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25565. // Six indices (two triangles) per face.
  25566. var verticesLength = positions.length / 3;
  25567. indices.push(verticesLength);
  25568. indices.push(verticesLength + 1);
  25569. indices.push(verticesLength + 2);
  25570. indices.push(verticesLength);
  25571. indices.push(verticesLength + 2);
  25572. indices.push(verticesLength + 3);
  25573. // Four vertices per face.
  25574. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25575. positions.push(vertex.x, vertex.y, vertex.z);
  25576. normals.push(normal.x, normal.y, normal.z);
  25577. uvs.push(faceUV[index].z, faceUV[index].w);
  25578. if (faceColors) {
  25579. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25580. }
  25581. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25582. positions.push(vertex.x, vertex.y, vertex.z);
  25583. normals.push(normal.x, normal.y, normal.z);
  25584. uvs.push(faceUV[index].x, faceUV[index].w);
  25585. if (faceColors) {
  25586. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25587. }
  25588. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25589. positions.push(vertex.x, vertex.y, vertex.z);
  25590. normals.push(normal.x, normal.y, normal.z);
  25591. uvs.push(faceUV[index].x, faceUV[index].y);
  25592. if (faceColors) {
  25593. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25594. }
  25595. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25596. positions.push(vertex.x, vertex.y, vertex.z);
  25597. normals.push(normal.x, normal.y, normal.z);
  25598. uvs.push(faceUV[index].z, faceUV[index].y);
  25599. if (faceColors) {
  25600. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25601. }
  25602. }
  25603. // sides
  25604. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25605. // Result
  25606. var vertexData = new VertexData();
  25607. vertexData.indices = indices;
  25608. vertexData.positions = positions;
  25609. vertexData.normals = normals;
  25610. vertexData.uvs = uvs;
  25611. if (faceColors) {
  25612. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25613. vertexData.colors = totalColors;
  25614. }
  25615. return vertexData;
  25616. };
  25617. /**
  25618. * Creates the VertexData of the Sphere.
  25619. */
  25620. VertexData.CreateSphere = function (options) {
  25621. var segments = options.segments || 32;
  25622. var diameterX = options.diameterX || options.diameter || 1;
  25623. var diameterY = options.diameterY || options.diameter || 1;
  25624. var diameterZ = options.diameterZ || options.diameter || 1;
  25625. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25626. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25627. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25628. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25629. var totalZRotationSteps = 2 + segments;
  25630. var totalYRotationSteps = 2 * totalZRotationSteps;
  25631. var indices = [];
  25632. var positions = [];
  25633. var normals = [];
  25634. var uvs = [];
  25635. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25636. var normalizedZ = zRotationStep / totalZRotationSteps;
  25637. var angleZ = normalizedZ * Math.PI * slice;
  25638. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25639. var normalizedY = yRotationStep / totalYRotationSteps;
  25640. var angleY = normalizedY * Math.PI * 2 * arc;
  25641. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25642. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25643. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25644. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25645. var vertex = complete.multiply(radius);
  25646. var normal = complete.divide(radius).normalize();
  25647. positions.push(vertex.x, vertex.y, vertex.z);
  25648. normals.push(normal.x, normal.y, normal.z);
  25649. uvs.push(normalizedY, normalizedZ);
  25650. }
  25651. if (zRotationStep > 0) {
  25652. var verticesCount = positions.length / 3;
  25653. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25654. indices.push((firstIndex));
  25655. indices.push((firstIndex + 1));
  25656. indices.push(firstIndex + totalYRotationSteps + 1);
  25657. indices.push((firstIndex + totalYRotationSteps + 1));
  25658. indices.push((firstIndex + 1));
  25659. indices.push((firstIndex + totalYRotationSteps + 2));
  25660. }
  25661. }
  25662. }
  25663. // Sides
  25664. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25665. // Result
  25666. var vertexData = new VertexData();
  25667. vertexData.indices = indices;
  25668. vertexData.positions = positions;
  25669. vertexData.normals = normals;
  25670. vertexData.uvs = uvs;
  25671. return vertexData;
  25672. };
  25673. /**
  25674. * Creates the VertexData of the Cylinder or Cone.
  25675. */
  25676. VertexData.CreateCylinder = function (options) {
  25677. var height = options.height || 2;
  25678. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25679. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25680. var tessellation = options.tessellation || 24;
  25681. var subdivisions = options.subdivisions || 1;
  25682. var hasRings = options.hasRings;
  25683. var enclose = options.enclose;
  25684. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25685. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25686. var faceUV = options.faceUV || new Array(3);
  25687. var faceColors = options.faceColors;
  25688. // default face colors and UV if undefined
  25689. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25690. var ringNb = (hasRings) ? subdivisions : 1;
  25691. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25692. var f;
  25693. for (f = 0; f < surfaceNb; f++) {
  25694. if (faceColors && faceColors[f] === undefined) {
  25695. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25696. }
  25697. }
  25698. for (f = 0; f < surfaceNb; f++) {
  25699. if (faceUV && faceUV[f] === undefined) {
  25700. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25701. }
  25702. }
  25703. var indices = [];
  25704. var positions = [];
  25705. var normals = [];
  25706. var uvs = [];
  25707. var colors = [];
  25708. var angle_step = Math.PI * 2 * arc / tessellation;
  25709. var angle;
  25710. var h;
  25711. var radius;
  25712. var tan = (diameterBottom - diameterTop) / 2 / height;
  25713. var ringVertex = BABYLON.Vector3.Zero();
  25714. var ringNormal = BABYLON.Vector3.Zero();
  25715. var ringFirstVertex = BABYLON.Vector3.Zero();
  25716. var ringFirstNormal = BABYLON.Vector3.Zero();
  25717. var quadNormal = BABYLON.Vector3.Zero();
  25718. var Y = BABYLON.Axis.Y;
  25719. // positions, normals, uvs
  25720. var i;
  25721. var j;
  25722. var r;
  25723. var ringIdx = 1;
  25724. var s = 1; // surface index
  25725. var cs = 0;
  25726. var v = 0;
  25727. for (i = 0; i <= subdivisions; i++) {
  25728. h = i / subdivisions;
  25729. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25730. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25731. for (r = 0; r < ringIdx; r++) {
  25732. if (hasRings) {
  25733. s += r;
  25734. }
  25735. if (enclose) {
  25736. s += 2 * r;
  25737. }
  25738. for (j = 0; j <= tessellation; j++) {
  25739. angle = j * angle_step;
  25740. // position
  25741. ringVertex.x = Math.cos(-angle) * radius;
  25742. ringVertex.y = -height / 2 + h * height;
  25743. ringVertex.z = Math.sin(-angle) * radius;
  25744. // normal
  25745. if (diameterTop === 0 && i === subdivisions) {
  25746. // if no top cap, reuse former normals
  25747. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25748. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25749. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25750. }
  25751. else {
  25752. ringNormal.x = ringVertex.x;
  25753. ringNormal.z = ringVertex.z;
  25754. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25755. ringNormal.normalize();
  25756. }
  25757. // keep first ring vertex values for enclose
  25758. if (j === 0) {
  25759. ringFirstVertex.copyFrom(ringVertex);
  25760. ringFirstNormal.copyFrom(ringNormal);
  25761. }
  25762. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25763. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25764. if (hasRings) {
  25765. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25766. }
  25767. else {
  25768. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25769. }
  25770. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25771. if (faceColors) {
  25772. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25773. }
  25774. }
  25775. // if enclose, add four vertices and their dedicated normals
  25776. if (arc !== 1 && enclose) {
  25777. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25778. positions.push(0, ringVertex.y, 0);
  25779. positions.push(0, ringVertex.y, 0);
  25780. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25781. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25782. quadNormal.normalize();
  25783. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25784. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25785. quadNormal.normalize();
  25786. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25787. if (hasRings) {
  25788. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25789. }
  25790. else {
  25791. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25792. }
  25793. uvs.push(faceUV[s + 1].x, v);
  25794. uvs.push(faceUV[s + 1].z, v);
  25795. if (hasRings) {
  25796. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25797. }
  25798. else {
  25799. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25800. }
  25801. uvs.push(faceUV[s + 2].x, v);
  25802. uvs.push(faceUV[s + 2].z, v);
  25803. if (faceColors) {
  25804. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25805. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25806. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25807. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25808. }
  25809. }
  25810. if (cs !== s) {
  25811. cs = s;
  25812. }
  25813. }
  25814. }
  25815. // indices
  25816. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25817. var s;
  25818. i = 0;
  25819. for (s = 0; s < subdivisions; s++) {
  25820. for (j = 0; j < tessellation; j++) {
  25821. var i0 = i * (e + 1) + j;
  25822. var i1 = (i + 1) * (e + 1) + j;
  25823. var i2 = i * (e + 1) + (j + 1);
  25824. var i3 = (i + 1) * (e + 1) + (j + 1);
  25825. indices.push(i0, i1, i2);
  25826. indices.push(i3, i2, i1);
  25827. }
  25828. if (arc !== 1 && enclose) {
  25829. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25830. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25831. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25832. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25833. }
  25834. i = (hasRings) ? (i + 2) : (i + 1);
  25835. }
  25836. // Caps
  25837. var createCylinderCap = function (isTop) {
  25838. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25839. if (radius === 0) {
  25840. return;
  25841. }
  25842. // Cap positions, normals & uvs
  25843. var angle;
  25844. var circleVector;
  25845. var i;
  25846. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25847. var c;
  25848. if (faceColors) {
  25849. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25850. }
  25851. // cap center
  25852. var vbase = positions.length / 3;
  25853. var offset = isTop ? height / 2 : -height / 2;
  25854. var center = new BABYLON.Vector3(0, offset, 0);
  25855. positions.push(center.x, center.y, center.z);
  25856. normals.push(0, isTop ? 1 : -1, 0);
  25857. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25858. if (faceColors) {
  25859. colors.push(c.r, c.g, c.b, c.a);
  25860. }
  25861. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25862. for (i = 0; i <= tessellation; i++) {
  25863. angle = Math.PI * 2 * i * arc / tessellation;
  25864. var cos = Math.cos(-angle);
  25865. var sin = Math.sin(-angle);
  25866. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25867. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25868. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25869. normals.push(0, isTop ? 1 : -1, 0);
  25870. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25871. if (faceColors) {
  25872. colors.push(c.r, c.g, c.b, c.a);
  25873. }
  25874. }
  25875. // Cap indices
  25876. for (i = 0; i < tessellation; i++) {
  25877. if (!isTop) {
  25878. indices.push(vbase);
  25879. indices.push(vbase + (i + 1));
  25880. indices.push(vbase + (i + 2));
  25881. }
  25882. else {
  25883. indices.push(vbase);
  25884. indices.push(vbase + (i + 2));
  25885. indices.push(vbase + (i + 1));
  25886. }
  25887. }
  25888. };
  25889. // add caps to geometry
  25890. createCylinderCap(false);
  25891. createCylinderCap(true);
  25892. // Sides
  25893. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25894. var vertexData = new VertexData();
  25895. vertexData.indices = indices;
  25896. vertexData.positions = positions;
  25897. vertexData.normals = normals;
  25898. vertexData.uvs = uvs;
  25899. if (faceColors) {
  25900. vertexData.colors = colors;
  25901. }
  25902. return vertexData;
  25903. };
  25904. /**
  25905. * Creates the VertexData of the Torus.
  25906. */
  25907. VertexData.CreateTorus = function (options) {
  25908. var indices = [];
  25909. var positions = [];
  25910. var normals = [];
  25911. var uvs = [];
  25912. var diameter = options.diameter || 1;
  25913. var thickness = options.thickness || 0.5;
  25914. var tessellation = options.tessellation || 16;
  25915. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25916. var stride = tessellation + 1;
  25917. for (var i = 0; i <= tessellation; i++) {
  25918. var u = i / tessellation;
  25919. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25920. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25921. for (var j = 0; j <= tessellation; j++) {
  25922. var v = 1 - j / tessellation;
  25923. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25924. var dx = Math.cos(innerAngle);
  25925. var dy = Math.sin(innerAngle);
  25926. // Create a vertex.
  25927. var normal = new BABYLON.Vector3(dx, dy, 0);
  25928. var position = normal.scale(thickness / 2);
  25929. var textureCoordinate = new BABYLON.Vector2(u, v);
  25930. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25931. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25932. positions.push(position.x, position.y, position.z);
  25933. normals.push(normal.x, normal.y, normal.z);
  25934. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25935. // And create indices for two triangles.
  25936. var nextI = (i + 1) % stride;
  25937. var nextJ = (j + 1) % stride;
  25938. indices.push(i * stride + j);
  25939. indices.push(i * stride + nextJ);
  25940. indices.push(nextI * stride + j);
  25941. indices.push(i * stride + nextJ);
  25942. indices.push(nextI * stride + nextJ);
  25943. indices.push(nextI * stride + j);
  25944. }
  25945. }
  25946. // Sides
  25947. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25948. // Result
  25949. var vertexData = new VertexData();
  25950. vertexData.indices = indices;
  25951. vertexData.positions = positions;
  25952. vertexData.normals = normals;
  25953. vertexData.uvs = uvs;
  25954. return vertexData;
  25955. };
  25956. /**
  25957. * Creates the VertexData of the LineSystem.
  25958. */
  25959. VertexData.CreateLineSystem = function (options) {
  25960. var indices = [];
  25961. var positions = [];
  25962. var lines = options.lines;
  25963. var idx = 0;
  25964. for (var l = 0; l < lines.length; l++) {
  25965. var points = lines[l];
  25966. for (var index = 0; index < points.length; index++) {
  25967. positions.push(points[index].x, points[index].y, points[index].z);
  25968. if (index > 0) {
  25969. indices.push(idx - 1);
  25970. indices.push(idx);
  25971. }
  25972. idx++;
  25973. }
  25974. }
  25975. var vertexData = new VertexData();
  25976. vertexData.indices = indices;
  25977. vertexData.positions = positions;
  25978. return vertexData;
  25979. };
  25980. /**
  25981. * Create the VertexData of the DashedLines.
  25982. */
  25983. VertexData.CreateDashedLines = function (options) {
  25984. var dashSize = options.dashSize || 3;
  25985. var gapSize = options.gapSize || 1;
  25986. var dashNb = options.dashNb || 200;
  25987. var points = options.points;
  25988. var positions = new Array();
  25989. var indices = new Array();
  25990. var curvect = BABYLON.Vector3.Zero();
  25991. var lg = 0;
  25992. var nb = 0;
  25993. var shft = 0;
  25994. var dashshft = 0;
  25995. var curshft = 0;
  25996. var idx = 0;
  25997. var i = 0;
  25998. for (i = 0; i < points.length - 1; i++) {
  25999. points[i + 1].subtractToRef(points[i], curvect);
  26000. lg += curvect.length();
  26001. }
  26002. shft = lg / dashNb;
  26003. dashshft = dashSize * shft / (dashSize + gapSize);
  26004. for (i = 0; i < points.length - 1; i++) {
  26005. points[i + 1].subtractToRef(points[i], curvect);
  26006. nb = Math.floor(curvect.length() / shft);
  26007. curvect.normalize();
  26008. for (var j = 0; j < nb; j++) {
  26009. curshft = shft * j;
  26010. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26011. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26012. indices.push(idx, idx + 1);
  26013. idx += 2;
  26014. }
  26015. }
  26016. // Result
  26017. var vertexData = new VertexData();
  26018. vertexData.positions = positions;
  26019. vertexData.indices = indices;
  26020. return vertexData;
  26021. };
  26022. /**
  26023. * Creates the VertexData of the Ground.
  26024. */
  26025. VertexData.CreateGround = function (options) {
  26026. var indices = [];
  26027. var positions = [];
  26028. var normals = [];
  26029. var uvs = [];
  26030. var row, col;
  26031. var width = options.width || 1;
  26032. var height = options.height || 1;
  26033. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26034. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26035. for (row = 0; row <= subdivisionsY; row++) {
  26036. for (col = 0; col <= subdivisionsX; col++) {
  26037. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  26038. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26039. positions.push(position.x, position.y, position.z);
  26040. normals.push(normal.x, normal.y, normal.z);
  26041. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  26042. }
  26043. }
  26044. for (row = 0; row < subdivisionsY; row++) {
  26045. for (col = 0; col < subdivisionsX; col++) {
  26046. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26047. indices.push(col + 1 + row * (subdivisionsX + 1));
  26048. indices.push(col + row * (subdivisionsX + 1));
  26049. indices.push(col + (row + 1) * (subdivisionsX + 1));
  26050. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26051. indices.push(col + row * (subdivisionsX + 1));
  26052. }
  26053. }
  26054. // Result
  26055. var vertexData = new VertexData();
  26056. vertexData.indices = indices;
  26057. vertexData.positions = positions;
  26058. vertexData.normals = normals;
  26059. vertexData.uvs = uvs;
  26060. return vertexData;
  26061. };
  26062. /**
  26063. * Creates the VertexData of the TiledGround.
  26064. */
  26065. VertexData.CreateTiledGround = function (options) {
  26066. var xmin = options.xmin || -1.0;
  26067. var zmin = options.zmin || -1.0;
  26068. var xmax = options.xmax || 1.0;
  26069. var zmax = options.zmax || 1.0;
  26070. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  26071. var precision = options.precision || { w: 1, h: 1 };
  26072. var indices = [];
  26073. var positions = [];
  26074. var normals = [];
  26075. var uvs = [];
  26076. var row, col, tileRow, tileCol;
  26077. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  26078. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26079. precision.w = (precision.w < 1) ? 1 : precision.w;
  26080. precision.h = (precision.h < 1) ? 1 : precision.h;
  26081. var tileSize = {
  26082. 'w': (xmax - xmin) / subdivisions.w,
  26083. 'h': (zmax - zmin) / subdivisions.h
  26084. };
  26085. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26086. // Indices
  26087. var base = positions.length / 3;
  26088. var rowLength = precision.w + 1;
  26089. for (row = 0; row < precision.h; row++) {
  26090. for (col = 0; col < precision.w; col++) {
  26091. var square = [
  26092. base + col + row * rowLength,
  26093. base + (col + 1) + row * rowLength,
  26094. base + (col + 1) + (row + 1) * rowLength,
  26095. base + col + (row + 1) * rowLength
  26096. ];
  26097. indices.push(square[1]);
  26098. indices.push(square[2]);
  26099. indices.push(square[3]);
  26100. indices.push(square[0]);
  26101. indices.push(square[1]);
  26102. indices.push(square[3]);
  26103. }
  26104. }
  26105. // Position, normals and uvs
  26106. var position = BABYLON.Vector3.Zero();
  26107. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26108. for (row = 0; row <= precision.h; row++) {
  26109. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26110. for (col = 0; col <= precision.w; col++) {
  26111. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26112. position.y = 0;
  26113. positions.push(position.x, position.y, position.z);
  26114. normals.push(normal.x, normal.y, normal.z);
  26115. uvs.push(col / precision.w, row / precision.h);
  26116. }
  26117. }
  26118. }
  26119. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26120. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26121. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26122. }
  26123. }
  26124. // Result
  26125. var vertexData = new VertexData();
  26126. vertexData.indices = indices;
  26127. vertexData.positions = positions;
  26128. vertexData.normals = normals;
  26129. vertexData.uvs = uvs;
  26130. return vertexData;
  26131. };
  26132. /**
  26133. * Creates the VertexData of the Ground designed from a heightmap.
  26134. */
  26135. VertexData.CreateGroundFromHeightMap = function (options) {
  26136. var indices = [];
  26137. var positions = [];
  26138. var normals = [];
  26139. var uvs = [];
  26140. var row, col;
  26141. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26142. // Vertices
  26143. for (row = 0; row <= options.subdivisions; row++) {
  26144. for (col = 0; col <= options.subdivisions; col++) {
  26145. 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));
  26146. // Compute height
  26147. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  26148. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  26149. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  26150. var r = options.buffer[pos] / 255.0;
  26151. var g = options.buffer[pos + 1] / 255.0;
  26152. var b = options.buffer[pos + 2] / 255.0;
  26153. var gradient = r * filter.r + g * filter.g + b * filter.b;
  26154. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  26155. // Add vertex
  26156. positions.push(position.x, position.y, position.z);
  26157. normals.push(0, 0, 0);
  26158. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  26159. }
  26160. }
  26161. // Indices
  26162. for (row = 0; row < options.subdivisions; row++) {
  26163. for (col = 0; col < options.subdivisions; col++) {
  26164. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26165. indices.push(col + 1 + row * (options.subdivisions + 1));
  26166. indices.push(col + row * (options.subdivisions + 1));
  26167. indices.push(col + (row + 1) * (options.subdivisions + 1));
  26168. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26169. indices.push(col + row * (options.subdivisions + 1));
  26170. }
  26171. }
  26172. // Normals
  26173. VertexData.ComputeNormals(positions, indices, normals);
  26174. // Result
  26175. var vertexData = new VertexData();
  26176. vertexData.indices = indices;
  26177. vertexData.positions = positions;
  26178. vertexData.normals = normals;
  26179. vertexData.uvs = uvs;
  26180. return vertexData;
  26181. };
  26182. /**
  26183. * Creates the VertexData of the Plane.
  26184. */
  26185. VertexData.CreatePlane = function (options) {
  26186. var indices = [];
  26187. var positions = [];
  26188. var normals = [];
  26189. var uvs = [];
  26190. var width = options.width || options.size || 1;
  26191. var height = options.height || options.size || 1;
  26192. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26193. // Vertices
  26194. var halfWidth = width / 2.0;
  26195. var halfHeight = height / 2.0;
  26196. positions.push(-halfWidth, -halfHeight, 0);
  26197. normals.push(0, 0, -1.0);
  26198. uvs.push(0.0, 0.0);
  26199. positions.push(halfWidth, -halfHeight, 0);
  26200. normals.push(0, 0, -1.0);
  26201. uvs.push(1.0, 0.0);
  26202. positions.push(halfWidth, halfHeight, 0);
  26203. normals.push(0, 0, -1.0);
  26204. uvs.push(1.0, 1.0);
  26205. positions.push(-halfWidth, halfHeight, 0);
  26206. normals.push(0, 0, -1.0);
  26207. uvs.push(0.0, 1.0);
  26208. // Indices
  26209. indices.push(0);
  26210. indices.push(1);
  26211. indices.push(2);
  26212. indices.push(0);
  26213. indices.push(2);
  26214. indices.push(3);
  26215. // Sides
  26216. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26217. // Result
  26218. var vertexData = new VertexData();
  26219. vertexData.indices = indices;
  26220. vertexData.positions = positions;
  26221. vertexData.normals = normals;
  26222. vertexData.uvs = uvs;
  26223. return vertexData;
  26224. };
  26225. /**
  26226. * Creates the VertexData of the Disc or regular Polygon.
  26227. */
  26228. VertexData.CreateDisc = function (options) {
  26229. var positions = [];
  26230. var indices = [];
  26231. var normals = [];
  26232. var uvs = [];
  26233. var radius = options.radius || 0.5;
  26234. var tessellation = options.tessellation || 64;
  26235. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26236. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26237. // positions and uvs
  26238. positions.push(0, 0, 0); // disc center first
  26239. uvs.push(0.5, 0.5);
  26240. var theta = Math.PI * 2 * arc;
  26241. var step = theta / tessellation;
  26242. for (var a = 0; a < theta; a += step) {
  26243. var x = Math.cos(a);
  26244. var y = Math.sin(a);
  26245. var u = (x + 1) / 2;
  26246. var v = (1 - y) / 2;
  26247. positions.push(radius * x, radius * y, 0);
  26248. uvs.push(u, v);
  26249. }
  26250. if (arc === 1) {
  26251. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26252. uvs.push(uvs[2], uvs[3]);
  26253. }
  26254. //indices
  26255. var vertexNb = positions.length / 3;
  26256. for (var i = 1; i < vertexNb - 1; i++) {
  26257. indices.push(i + 1, 0, i);
  26258. }
  26259. // result
  26260. VertexData.ComputeNormals(positions, indices, normals);
  26261. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26262. var vertexData = new VertexData();
  26263. vertexData.indices = indices;
  26264. vertexData.positions = positions;
  26265. vertexData.normals = normals;
  26266. vertexData.uvs = uvs;
  26267. return vertexData;
  26268. };
  26269. /**
  26270. * Re-creates the VertexData of the Polygon for sideOrientation.
  26271. */
  26272. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26273. var faceUV = fUV || new Array(3);
  26274. var faceColors = fColors;
  26275. var colors = [];
  26276. // default face colors and UV if undefined
  26277. for (var f = 0; f < 3; f++) {
  26278. if (faceUV[f] === undefined) {
  26279. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26280. }
  26281. if (faceColors && faceColors[f] === undefined) {
  26282. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26283. }
  26284. }
  26285. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26286. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26287. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26288. var indices = polygon.getIndices();
  26289. // set face colours and textures
  26290. var idx = 0;
  26291. var face = 0;
  26292. for (var index = 0; index < normals.length; index += 3) {
  26293. //Edge Face no. 1
  26294. if (Math.abs(normals[index + 1]) == 0) {
  26295. face = 1;
  26296. }
  26297. //Top Face no. 0
  26298. if (normals[index + 1] == 1) {
  26299. face = 0;
  26300. }
  26301. //Bottom Face no. 2
  26302. if (normals[index + 1] == -1) {
  26303. face = 2;
  26304. }
  26305. idx = index / 3;
  26306. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26307. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26308. if (faceColors) {
  26309. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26310. }
  26311. }
  26312. // sides
  26313. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26314. // Result
  26315. var vertexData = new VertexData();
  26316. vertexData.indices = indices;
  26317. vertexData.positions = positions;
  26318. vertexData.normals = normals;
  26319. vertexData.uvs = uvs;
  26320. if (faceColors) {
  26321. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26322. vertexData.colors = totalColors;
  26323. }
  26324. return vertexData;
  26325. };
  26326. /**
  26327. * Creates the VertexData of the IcoSphere.
  26328. */
  26329. VertexData.CreateIcoSphere = function (options) {
  26330. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26331. var radius = options.radius || 1;
  26332. var flat = (options.flat === undefined) ? true : options.flat;
  26333. var subdivisions = options.subdivisions || 4;
  26334. var radiusX = options.radiusX || radius;
  26335. var radiusY = options.radiusY || radius;
  26336. var radiusZ = options.radiusZ || radius;
  26337. var t = (1 + Math.sqrt(5)) / 2;
  26338. // 12 vertex x,y,z
  26339. var ico_vertices = [
  26340. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26341. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26342. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26343. ];
  26344. // index of 3 vertex makes a face of icopshere
  26345. var ico_indices = [
  26346. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26347. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26348. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26349. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26350. ];
  26351. // vertex for uv have aliased position, not for UV
  26352. var vertices_unalias_id = [
  26353. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26354. // vertex alias
  26355. 0,
  26356. 2,
  26357. 3,
  26358. 3,
  26359. 3,
  26360. 4,
  26361. 7,
  26362. 8,
  26363. 9,
  26364. 9,
  26365. 10,
  26366. 11 // 23: B + 12
  26367. ];
  26368. // uv as integer step (not pixels !)
  26369. var ico_vertexuv = [
  26370. 5, 1, 3, 1, 6, 4, 0, 0,
  26371. 5, 3, 4, 2, 2, 2, 4, 0,
  26372. 2, 0, 1, 1, 6, 0, 6, 2,
  26373. // vertex alias (for same vertex on different faces)
  26374. 0, 4,
  26375. 3, 3,
  26376. 4, 4,
  26377. 3, 1,
  26378. 4, 2,
  26379. 4, 4,
  26380. 0, 2,
  26381. 1, 1,
  26382. 2, 2,
  26383. 3, 3,
  26384. 1, 3,
  26385. 2, 4 // 23: B + 12
  26386. ];
  26387. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26388. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26389. // First island of uv mapping
  26390. // v = 4h 3+ 2
  26391. // v = 3h 9+ 4
  26392. // v = 2h 9+ 5 B
  26393. // v = 1h 9 1 0
  26394. // v = 0h 3 8 7 A
  26395. // u = 0 1 2 3 4 5 6 *a
  26396. // Second island of uv mapping
  26397. // v = 4h 0+ B+ 4+
  26398. // v = 3h A+ 2+
  26399. // v = 2h 7+ 6 3+
  26400. // v = 1h 8+ 3+
  26401. // v = 0h
  26402. // u = 0 1 2 3 4 5 6 *a
  26403. // Face layout on texture UV mapping
  26404. // ============
  26405. // \ 4 /\ 16 / ======
  26406. // \ / \ / /\ 11 /
  26407. // \/ 7 \/ / \ /
  26408. // ======= / 10 \/
  26409. // /\ 17 /\ =======
  26410. // / \ / \ \ 15 /\
  26411. // / 8 \/ 12 \ \ / \
  26412. // ============ \/ 6 \
  26413. // \ 18 /\ ============
  26414. // \ / \ \ 5 /\ 0 /
  26415. // \/ 13 \ \ / \ /
  26416. // ======= \/ 1 \/
  26417. // =============
  26418. // /\ 19 /\ 2 /\
  26419. // / \ / \ / \
  26420. // / 14 \/ 9 \/ 3 \
  26421. // ===================
  26422. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26423. var ustep = 138 / 1024;
  26424. var vstep = 239 / 1024;
  26425. var uoffset = 60 / 1024;
  26426. var voffset = 26 / 1024;
  26427. // Second island should have margin, not to touch the first island
  26428. // avoid any borderline artefact in pixel rounding
  26429. var island_u_offset = -40 / 1024;
  26430. var island_v_offset = +20 / 1024;
  26431. // face is either island 0 or 1 :
  26432. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26433. var island = [
  26434. 0, 0, 0, 0, 1,
  26435. 0, 0, 1, 1, 0,
  26436. 0, 0, 1, 1, 0,
  26437. 0, 1, 1, 1, 0 // 15 - 19
  26438. ];
  26439. var indices = [];
  26440. var positions = [];
  26441. var normals = [];
  26442. var uvs = [];
  26443. var current_indice = 0;
  26444. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26445. var face_vertex_pos = new Array(3);
  26446. var face_vertex_uv = new Array(3);
  26447. var v012;
  26448. for (v012 = 0; v012 < 3; v012++) {
  26449. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26450. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26451. }
  26452. // create all with normals
  26453. for (var face = 0; face < 20; face++) {
  26454. // 3 vertex per face
  26455. for (v012 = 0; v012 < 3; v012++) {
  26456. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26457. var v_id = ico_indices[3 * face + v012];
  26458. // vertex have 3D position (x,y,z)
  26459. 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]);
  26460. // Normalize to get normal, then scale to radius
  26461. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26462. // uv Coordinates from vertex ID
  26463. 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);
  26464. }
  26465. // Subdivide the face (interpolate pos, norm, uv)
  26466. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26467. // - norm is linear interpolation of vertex corner normal
  26468. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26469. // - uv is linear interpolation
  26470. //
  26471. // Topology is as below for sub-divide by 2
  26472. // vertex shown as v0,v1,v2
  26473. // interp index is i1 to progress in range [v0,v1[
  26474. // interp index is i2 to progress in range [v0,v2[
  26475. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26476. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26477. //
  26478. //
  26479. // i2 v2
  26480. // ^ ^
  26481. // / / \
  26482. // / / \
  26483. // / / \
  26484. // / / (0,1) \
  26485. // / #---------\
  26486. // / / \ (0,0)'/ \
  26487. // / / \ / \
  26488. // / / \ / \
  26489. // / / (0,0) \ / (1,0) \
  26490. // / #---------#---------\
  26491. // v0 v1
  26492. //
  26493. // --------------------> i1
  26494. //
  26495. // interp of (i1,i2):
  26496. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26497. // along i1 : lerp(x0,x1, i1/(S-i2))
  26498. //
  26499. // centroid of triangle is needed to get help normal computation
  26500. // (c1,c2) are used for centroid location
  26501. var interp_vertex = function (i1, i2, c1, c2) {
  26502. // vertex is interpolated from
  26503. // - face_vertex_pos[0..2]
  26504. // - face_vertex_uv[0..2]
  26505. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26506. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26507. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26508. pos_interp.normalize();
  26509. var vertex_normal;
  26510. if (flat) {
  26511. // in flat mode, recalculate normal as face centroid normal
  26512. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26513. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26514. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26515. }
  26516. else {
  26517. // in smooth mode, recalculate normal from each single vertex position
  26518. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26519. }
  26520. // Vertex normal need correction due to X,Y,Z radius scaling
  26521. vertex_normal.x /= radiusX;
  26522. vertex_normal.y /= radiusY;
  26523. vertex_normal.z /= radiusZ;
  26524. vertex_normal.normalize();
  26525. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26526. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26527. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26528. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26529. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26530. uvs.push(uv_interp.x, uv_interp.y);
  26531. // push each vertex has member of a face
  26532. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26533. indices.push(current_indice);
  26534. current_indice++;
  26535. };
  26536. for (var i2 = 0; i2 < subdivisions; i2++) {
  26537. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26538. // face : (i1,i2) for /\ :
  26539. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26540. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26541. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26542. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26543. if (i1 + i2 + 1 < subdivisions) {
  26544. // face : (i1,i2)' for \/ :
  26545. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26546. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26547. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26548. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26549. }
  26550. }
  26551. }
  26552. }
  26553. // Sides
  26554. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26555. // Result
  26556. var vertexData = new VertexData();
  26557. vertexData.indices = indices;
  26558. vertexData.positions = positions;
  26559. vertexData.normals = normals;
  26560. vertexData.uvs = uvs;
  26561. return vertexData;
  26562. };
  26563. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26564. /**
  26565. * Creates the VertexData of the Polyhedron.
  26566. */
  26567. VertexData.CreatePolyhedron = function (options) {
  26568. // provided polyhedron types :
  26569. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26570. // 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)
  26571. var polyhedra = [];
  26572. 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]] };
  26573. 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]] };
  26574. polyhedra[2] = {
  26575. 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]],
  26576. 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]]
  26577. };
  26578. polyhedra[3] = {
  26579. 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]],
  26580. 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]]
  26581. };
  26582. polyhedra[4] = {
  26583. 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]],
  26584. 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]]
  26585. };
  26586. 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]] };
  26587. 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]] };
  26588. 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]] };
  26589. 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]] };
  26590. 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]] };
  26591. 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]] };
  26592. 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]] };
  26593. 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]] };
  26594. 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]] };
  26595. polyhedra[14] = {
  26596. 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]],
  26597. 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]]
  26598. };
  26599. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26600. var size = options.size;
  26601. var sizeX = options.sizeX || size || 1;
  26602. var sizeY = options.sizeY || size || 1;
  26603. var sizeZ = options.sizeZ || size || 1;
  26604. var data = options.custom || polyhedra[type];
  26605. var nbfaces = data.face.length;
  26606. var faceUV = options.faceUV || new Array(nbfaces);
  26607. var faceColors = options.faceColors;
  26608. var flat = (options.flat === undefined) ? true : options.flat;
  26609. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26610. var positions = [];
  26611. var indices = [];
  26612. var normals = [];
  26613. var uvs = [];
  26614. var colors = [];
  26615. var index = 0;
  26616. var faceIdx = 0; // face cursor in the array "indexes"
  26617. var indexes = [];
  26618. var i = 0;
  26619. var f = 0;
  26620. var u, v, ang, x, y, tmp;
  26621. // default face colors and UV if undefined
  26622. if (flat) {
  26623. for (f = 0; f < nbfaces; f++) {
  26624. if (faceColors && faceColors[f] === undefined) {
  26625. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26626. }
  26627. if (faceUV && faceUV[f] === undefined) {
  26628. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26629. }
  26630. }
  26631. }
  26632. if (!flat) {
  26633. for (i = 0; i < data.vertex.length; i++) {
  26634. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26635. uvs.push(0, 0);
  26636. }
  26637. for (f = 0; f < nbfaces; f++) {
  26638. for (i = 0; i < data.face[f].length - 2; i++) {
  26639. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26640. }
  26641. }
  26642. }
  26643. else {
  26644. for (f = 0; f < nbfaces; f++) {
  26645. var fl = data.face[f].length; // number of vertices of the current face
  26646. ang = 2 * Math.PI / fl;
  26647. x = 0.5 * Math.tan(ang / 2);
  26648. y = 0.5;
  26649. // positions, uvs, colors
  26650. for (i = 0; i < fl; i++) {
  26651. // positions
  26652. 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);
  26653. indexes.push(index);
  26654. index++;
  26655. // uvs
  26656. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26657. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26658. uvs.push(u, v);
  26659. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26660. y = x * Math.sin(ang) + y * Math.cos(ang);
  26661. x = tmp;
  26662. // colors
  26663. if (faceColors) {
  26664. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26665. }
  26666. }
  26667. // indices from indexes
  26668. for (i = 0; i < fl - 2; i++) {
  26669. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26670. }
  26671. faceIdx += fl;
  26672. }
  26673. }
  26674. VertexData.ComputeNormals(positions, indices, normals);
  26675. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26676. var vertexData = new VertexData();
  26677. vertexData.positions = positions;
  26678. vertexData.indices = indices;
  26679. vertexData.normals = normals;
  26680. vertexData.uvs = uvs;
  26681. if (faceColors && flat) {
  26682. vertexData.colors = colors;
  26683. }
  26684. return vertexData;
  26685. };
  26686. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26687. /**
  26688. * Creates the VertexData of the Torus Knot.
  26689. */
  26690. VertexData.CreateTorusKnot = function (options) {
  26691. var indices = [];
  26692. var positions = [];
  26693. var normals = [];
  26694. var uvs = [];
  26695. var radius = options.radius || 2;
  26696. var tube = options.tube || 0.5;
  26697. var radialSegments = options.radialSegments || 32;
  26698. var tubularSegments = options.tubularSegments || 32;
  26699. var p = options.p || 2;
  26700. var q = options.q || 3;
  26701. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26702. // Helper
  26703. var getPos = function (angle) {
  26704. var cu = Math.cos(angle);
  26705. var su = Math.sin(angle);
  26706. var quOverP = q / p * angle;
  26707. var cs = Math.cos(quOverP);
  26708. var tx = radius * (2 + cs) * 0.5 * cu;
  26709. var ty = radius * (2 + cs) * su * 0.5;
  26710. var tz = radius * Math.sin(quOverP) * 0.5;
  26711. return new BABYLON.Vector3(tx, ty, tz);
  26712. };
  26713. // Vertices
  26714. var i;
  26715. var j;
  26716. for (i = 0; i <= radialSegments; i++) {
  26717. var modI = i % radialSegments;
  26718. var u = modI / radialSegments * 2 * p * Math.PI;
  26719. var p1 = getPos(u);
  26720. var p2 = getPos(u + 0.01);
  26721. var tang = p2.subtract(p1);
  26722. var n = p2.add(p1);
  26723. var bitan = BABYLON.Vector3.Cross(tang, n);
  26724. n = BABYLON.Vector3.Cross(bitan, tang);
  26725. bitan.normalize();
  26726. n.normalize();
  26727. for (j = 0; j < tubularSegments; j++) {
  26728. var modJ = j % tubularSegments;
  26729. var v = modJ / tubularSegments * 2 * Math.PI;
  26730. var cx = -tube * Math.cos(v);
  26731. var cy = tube * Math.sin(v);
  26732. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26733. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26734. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26735. uvs.push(i / radialSegments);
  26736. uvs.push(j / tubularSegments);
  26737. }
  26738. }
  26739. for (i = 0; i < radialSegments; i++) {
  26740. for (j = 0; j < tubularSegments; j++) {
  26741. var jNext = (j + 1) % tubularSegments;
  26742. var a = i * tubularSegments + j;
  26743. var b = (i + 1) * tubularSegments + j;
  26744. var c = (i + 1) * tubularSegments + jNext;
  26745. var d = i * tubularSegments + jNext;
  26746. indices.push(d);
  26747. indices.push(b);
  26748. indices.push(a);
  26749. indices.push(d);
  26750. indices.push(c);
  26751. indices.push(b);
  26752. }
  26753. }
  26754. // Normals
  26755. VertexData.ComputeNormals(positions, indices, normals);
  26756. // Sides
  26757. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26758. // Result
  26759. var vertexData = new VertexData();
  26760. vertexData.indices = indices;
  26761. vertexData.positions = positions;
  26762. vertexData.normals = normals;
  26763. vertexData.uvs = uvs;
  26764. return vertexData;
  26765. };
  26766. // Tools
  26767. /**
  26768. * @param {any} - positions (number[] or Float32Array)
  26769. * @param {any} - indices (number[] or Uint16Array)
  26770. * @param {any} - normals (number[] or Float32Array)
  26771. * options (optional) :
  26772. * facetPositions : optional array of facet positions (vector3)
  26773. * facetNormals : optional array of facet normals (vector3)
  26774. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26775. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26776. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26777. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26778. * bInfo : optional bounding info, required for facetPartitioning computation
  26779. */
  26780. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26781. // temporary scalar variables
  26782. var index = 0; // facet index
  26783. var p1p2x = 0.0; // p1p2 vector x coordinate
  26784. var p1p2y = 0.0; // p1p2 vector y coordinate
  26785. var p1p2z = 0.0; // p1p2 vector z coordinate
  26786. var p3p2x = 0.0; // p3p2 vector x coordinate
  26787. var p3p2y = 0.0; // p3p2 vector y coordinate
  26788. var p3p2z = 0.0; // p3p2 vector z coordinate
  26789. var faceNormalx = 0.0; // facet normal x coordinate
  26790. var faceNormaly = 0.0; // facet normal y coordinate
  26791. var faceNormalz = 0.0; // facet normal z coordinate
  26792. var length = 0.0; // facet normal length before normalization
  26793. var v1x = 0; // vector1 x index in the positions array
  26794. var v1y = 0; // vector1 y index in the positions array
  26795. var v1z = 0; // vector1 z index in the positions array
  26796. var v2x = 0; // vector2 x index in the positions array
  26797. var v2y = 0; // vector2 y index in the positions array
  26798. var v2z = 0; // vector2 z index in the positions array
  26799. var v3x = 0; // vector3 x index in the positions array
  26800. var v3y = 0; // vector3 y index in the positions array
  26801. var v3z = 0; // vector3 z index in the positions array
  26802. var computeFacetNormals = false;
  26803. var computeFacetPositions = false;
  26804. var computeFacetPartitioning = false;
  26805. var faceNormalSign = 1;
  26806. if (options) {
  26807. computeFacetNormals = (options.facetNormals) ? true : false;
  26808. computeFacetPositions = (options.facetPositions) ? true : false;
  26809. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26810. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26811. }
  26812. // facetPartitioning reinit if needed
  26813. if (computeFacetPartitioning) {
  26814. var ox = 0; // X partitioning index for facet position
  26815. var oy = 0; // Y partinioning index for facet position
  26816. var oz = 0; // Z partinioning index for facet position
  26817. var b1x = 0; // X partitioning index for facet v1 vertex
  26818. var b1y = 0; // Y partitioning index for facet v1 vertex
  26819. var b1z = 0; // z partitioning index for facet v1 vertex
  26820. var b2x = 0; // X partitioning index for facet v2 vertex
  26821. var b2y = 0; // Y partitioning index for facet v2 vertex
  26822. var b2z = 0; // Z partitioning index for facet v2 vertex
  26823. var b3x = 0; // X partitioning index for facet v3 vertex
  26824. var b3y = 0; // Y partitioning index for facet v3 vertex
  26825. var b3z = 0; // Z partitioning index for facet v3 vertex
  26826. var block_idx_o = 0; // facet barycenter block index
  26827. var block_idx_v1 = 0; // v1 vertex block index
  26828. var block_idx_v2 = 0; // v2 vertex block index
  26829. var block_idx_v3 = 0; // v3 vertex block index
  26830. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26831. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26832. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26833. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26834. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26835. var subSq = options.subDiv.max * options.subDiv.max;
  26836. options.facetPartitioning.length = 0;
  26837. }
  26838. // reset the normals
  26839. for (index = 0; index < positions.length; index++) {
  26840. normals[index] = 0.0;
  26841. }
  26842. // Loop : 1 indice triplet = 1 facet
  26843. var nbFaces = indices.length / 3;
  26844. for (index = 0; index < nbFaces; index++) {
  26845. // get the indexes of the coordinates of each vertex of the facet
  26846. v1x = indices[index * 3] * 3;
  26847. v1y = v1x + 1;
  26848. v1z = v1x + 2;
  26849. v2x = indices[index * 3 + 1] * 3;
  26850. v2y = v2x + 1;
  26851. v2z = v2x + 2;
  26852. v3x = indices[index * 3 + 2] * 3;
  26853. v3y = v3x + 1;
  26854. v3z = v3x + 2;
  26855. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26856. p1p2y = positions[v1y] - positions[v2y];
  26857. p1p2z = positions[v1z] - positions[v2z];
  26858. p3p2x = positions[v3x] - positions[v2x];
  26859. p3p2y = positions[v3y] - positions[v2y];
  26860. p3p2z = positions[v3z] - positions[v2z];
  26861. // compute the face normal with the cross product
  26862. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26863. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26864. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26865. // normalize this normal and store it in the array facetData
  26866. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26867. length = (length === 0) ? 1.0 : length;
  26868. faceNormalx /= length;
  26869. faceNormaly /= length;
  26870. faceNormalz /= length;
  26871. if (computeFacetNormals) {
  26872. options.facetNormals[index].x = faceNormalx;
  26873. options.facetNormals[index].y = faceNormaly;
  26874. options.facetNormals[index].z = faceNormalz;
  26875. }
  26876. if (computeFacetPositions) {
  26877. // compute and the facet barycenter coordinates in the array facetPositions
  26878. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26879. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26880. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26881. }
  26882. if (computeFacetPartitioning) {
  26883. // store the facet indexes in arrays in the main facetPartitioning array :
  26884. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26885. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26886. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26887. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26888. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26889. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26890. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26891. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26892. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26893. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26894. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26895. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26896. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26897. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26898. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26899. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26900. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26901. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26902. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26903. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26904. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26905. // push each facet index in each block containing the vertex
  26906. options.facetPartitioning[block_idx_v1].push(index);
  26907. if (block_idx_v2 != block_idx_v1) {
  26908. options.facetPartitioning[block_idx_v2].push(index);
  26909. }
  26910. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26911. options.facetPartitioning[block_idx_v3].push(index);
  26912. }
  26913. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26914. options.facetPartitioning[block_idx_o].push(index);
  26915. }
  26916. }
  26917. // compute the normals anyway
  26918. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26919. normals[v1y] += faceNormaly;
  26920. normals[v1z] += faceNormalz;
  26921. normals[v2x] += faceNormalx;
  26922. normals[v2y] += faceNormaly;
  26923. normals[v2z] += faceNormalz;
  26924. normals[v3x] += faceNormalx;
  26925. normals[v3y] += faceNormaly;
  26926. normals[v3z] += faceNormalz;
  26927. }
  26928. // last normalization of each normal
  26929. for (index = 0; index < normals.length / 3; index++) {
  26930. faceNormalx = normals[index * 3];
  26931. faceNormaly = normals[index * 3 + 1];
  26932. faceNormalz = normals[index * 3 + 2];
  26933. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26934. length = (length === 0) ? 1.0 : length;
  26935. faceNormalx /= length;
  26936. faceNormaly /= length;
  26937. faceNormalz /= length;
  26938. normals[index * 3] = faceNormalx;
  26939. normals[index * 3 + 1] = faceNormaly;
  26940. normals[index * 3 + 2] = faceNormalz;
  26941. }
  26942. };
  26943. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26944. var li = indices.length;
  26945. var ln = normals.length;
  26946. var i;
  26947. var n;
  26948. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26949. switch (sideOrientation) {
  26950. case BABYLON.Mesh.FRONTSIDE:
  26951. // nothing changed
  26952. break;
  26953. case BABYLON.Mesh.BACKSIDE:
  26954. var tmp;
  26955. // indices
  26956. for (i = 0; i < li; i += 3) {
  26957. tmp = indices[i];
  26958. indices[i] = indices[i + 2];
  26959. indices[i + 2] = tmp;
  26960. }
  26961. // normals
  26962. for (n = 0; n < ln; n++) {
  26963. normals[n] = -normals[n];
  26964. }
  26965. break;
  26966. case BABYLON.Mesh.DOUBLESIDE:
  26967. // positions
  26968. var lp = positions.length;
  26969. var l = lp / 3;
  26970. for (var p = 0; p < lp; p++) {
  26971. positions[lp + p] = positions[p];
  26972. }
  26973. // indices
  26974. for (i = 0; i < li; i += 3) {
  26975. indices[i + li] = indices[i + 2] + l;
  26976. indices[i + 1 + li] = indices[i + 1] + l;
  26977. indices[i + 2 + li] = indices[i] + l;
  26978. }
  26979. // normals
  26980. for (n = 0; n < ln; n++) {
  26981. normals[ln + n] = -normals[n];
  26982. }
  26983. // uvs
  26984. var lu = uvs.length;
  26985. var u = 0;
  26986. for (u = 0; u < lu; u++) {
  26987. uvs[u + lu] = uvs[u];
  26988. }
  26989. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26990. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26991. u = 0;
  26992. for (i = 0; i < lu / 2; i++) {
  26993. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  26994. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  26995. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  26996. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  26997. u += 2;
  26998. }
  26999. break;
  27000. }
  27001. };
  27002. /**
  27003. * Creates a new VertexData from the imported parameters.
  27004. */
  27005. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  27006. var vertexData = new VertexData();
  27007. // positions
  27008. var positions = parsedVertexData.positions;
  27009. if (positions) {
  27010. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27011. }
  27012. // normals
  27013. var normals = parsedVertexData.normals;
  27014. if (normals) {
  27015. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27016. }
  27017. // tangents
  27018. var tangents = parsedVertexData.tangents;
  27019. if (tangents) {
  27020. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  27021. }
  27022. // uvs
  27023. var uvs = parsedVertexData.uvs;
  27024. if (uvs) {
  27025. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27026. }
  27027. // uv2s
  27028. var uv2s = parsedVertexData.uv2s;
  27029. if (uv2s) {
  27030. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27031. }
  27032. // uv3s
  27033. var uv3s = parsedVertexData.uv3s;
  27034. if (uv3s) {
  27035. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27036. }
  27037. // uv4s
  27038. var uv4s = parsedVertexData.uv4s;
  27039. if (uv4s) {
  27040. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27041. }
  27042. // uv5s
  27043. var uv5s = parsedVertexData.uv5s;
  27044. if (uv5s) {
  27045. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27046. }
  27047. // uv6s
  27048. var uv6s = parsedVertexData.uv6s;
  27049. if (uv6s) {
  27050. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27051. }
  27052. // colors
  27053. var colors = parsedVertexData.colors;
  27054. if (colors) {
  27055. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27056. }
  27057. // matricesIndices
  27058. var matricesIndices = parsedVertexData.matricesIndices;
  27059. if (matricesIndices) {
  27060. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27061. }
  27062. // matricesWeights
  27063. var matricesWeights = parsedVertexData.matricesWeights;
  27064. if (matricesWeights) {
  27065. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27066. }
  27067. // indices
  27068. var indices = parsedVertexData.indices;
  27069. if (indices) {
  27070. vertexData.indices = indices;
  27071. }
  27072. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  27073. };
  27074. return VertexData;
  27075. }());
  27076. BABYLON.VertexData = VertexData;
  27077. })(BABYLON || (BABYLON = {}));
  27078. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  27079. var BABYLON;
  27080. (function (BABYLON) {
  27081. var Geometry = (function () {
  27082. function Geometry(id, scene, vertexData, updatable, mesh) {
  27083. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27084. this._totalVertices = 0;
  27085. this._isDisposed = false;
  27086. this.id = id;
  27087. this._engine = scene.getEngine();
  27088. this._meshes = [];
  27089. this._scene = scene;
  27090. //Init vertex buffer cache
  27091. this._vertexBuffers = {};
  27092. this._indices = [];
  27093. // vertexData
  27094. if (vertexData) {
  27095. this.setAllVerticesData(vertexData, updatable);
  27096. }
  27097. else {
  27098. this._totalVertices = 0;
  27099. this._indices = [];
  27100. }
  27101. if (this._engine.getCaps().vertexArrayObject) {
  27102. this._vertexArrayObjects = {};
  27103. }
  27104. // applyToMesh
  27105. if (mesh) {
  27106. if (mesh.getClassName() === "LinesMesh") {
  27107. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  27108. this.updateExtend();
  27109. }
  27110. this.applyToMesh(mesh);
  27111. mesh.computeWorldMatrix(true);
  27112. }
  27113. }
  27114. Object.defineProperty(Geometry.prototype, "boundingBias", {
  27115. /**
  27116. * 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
  27117. * @returns The Bias Vector
  27118. */
  27119. get: function () {
  27120. return this._boundingBias;
  27121. },
  27122. set: function (value) {
  27123. if (this._boundingBias && this._boundingBias.equals(value)) {
  27124. return;
  27125. }
  27126. this._boundingBias = value.clone();
  27127. this.updateBoundingInfo(true, null);
  27128. },
  27129. enumerable: true,
  27130. configurable: true
  27131. });
  27132. Object.defineProperty(Geometry.prototype, "extend", {
  27133. get: function () {
  27134. return this._extend;
  27135. },
  27136. enumerable: true,
  27137. configurable: true
  27138. });
  27139. Geometry.prototype.getScene = function () {
  27140. return this._scene;
  27141. };
  27142. Geometry.prototype.getEngine = function () {
  27143. return this._engine;
  27144. };
  27145. Geometry.prototype.isReady = function () {
  27146. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27147. };
  27148. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  27149. get: function () {
  27150. for (var index = 0; index < this._meshes.length; index++) {
  27151. if (!this._meshes[index].doNotSerialize) {
  27152. return false;
  27153. }
  27154. }
  27155. return true;
  27156. },
  27157. enumerable: true,
  27158. configurable: true
  27159. });
  27160. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27161. vertexData.applyToGeometry(this, updatable);
  27162. this.notifyUpdate();
  27163. };
  27164. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27165. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27166. this.setVerticesBuffer(buffer);
  27167. };
  27168. Geometry.prototype.removeVerticesData = function (kind) {
  27169. if (this._vertexBuffers[kind]) {
  27170. this._vertexBuffers[kind].dispose();
  27171. delete this._vertexBuffers[kind];
  27172. }
  27173. };
  27174. Geometry.prototype.setVerticesBuffer = function (buffer) {
  27175. var kind = buffer.getKind();
  27176. if (this._vertexBuffers[kind]) {
  27177. this._vertexBuffers[kind].dispose();
  27178. }
  27179. this._vertexBuffers[kind] = buffer;
  27180. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27181. var data = buffer.getData();
  27182. var stride = buffer.getStrideSize();
  27183. this._totalVertices = data.length / stride;
  27184. this.updateExtend(data, stride);
  27185. this._resetPointsArrayCache();
  27186. var meshes = this._meshes;
  27187. var numOfMeshes = meshes.length;
  27188. for (var index = 0; index < numOfMeshes; index++) {
  27189. var mesh = meshes[index];
  27190. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27191. mesh._createGlobalSubMesh();
  27192. mesh.computeWorldMatrix(true);
  27193. }
  27194. }
  27195. this.notifyUpdate(kind);
  27196. if (this._vertexArrayObjects) {
  27197. this._disposeVertexArrayObjects();
  27198. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  27199. }
  27200. };
  27201. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27202. var vertexBuffer = this.getVertexBuffer(kind);
  27203. if (!vertexBuffer) {
  27204. return;
  27205. }
  27206. vertexBuffer.updateDirectly(data, offset);
  27207. this.notifyUpdate(kind);
  27208. };
  27209. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27210. var vertexBuffer = this.getVertexBuffer(kind);
  27211. if (!vertexBuffer) {
  27212. return;
  27213. }
  27214. vertexBuffer.update(data);
  27215. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27216. var stride = vertexBuffer.getStrideSize();
  27217. this._totalVertices = data.length / stride;
  27218. this.updateBoundingInfo(updateExtends, data);
  27219. }
  27220. this.notifyUpdate(kind);
  27221. };
  27222. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  27223. if (updateExtends) {
  27224. this.updateExtend(data);
  27225. }
  27226. var meshes = this._meshes;
  27227. var numOfMeshes = meshes.length;
  27228. this._resetPointsArrayCache();
  27229. for (var index = 0; index < numOfMeshes; index++) {
  27230. var mesh = meshes[index];
  27231. if (updateExtends) {
  27232. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27233. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27234. var subMesh = mesh.subMeshes[subIndex];
  27235. subMesh.refreshBoundingInfo();
  27236. }
  27237. }
  27238. }
  27239. };
  27240. Geometry.prototype._bind = function (effect, indexToBind) {
  27241. if (indexToBind === void 0) { indexToBind = undefined; }
  27242. if (indexToBind === undefined) {
  27243. indexToBind = this._indexBuffer;
  27244. }
  27245. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  27246. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  27247. return;
  27248. }
  27249. // Using VAO
  27250. if (!this._vertexArrayObjects[effect.key]) {
  27251. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  27252. }
  27253. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  27254. };
  27255. Geometry.prototype.getTotalVertices = function () {
  27256. if (!this.isReady()) {
  27257. return 0;
  27258. }
  27259. return this._totalVertices;
  27260. };
  27261. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27262. var vertexBuffer = this.getVertexBuffer(kind);
  27263. if (!vertexBuffer) {
  27264. return null;
  27265. }
  27266. var orig = vertexBuffer.getData();
  27267. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  27268. return orig;
  27269. }
  27270. else {
  27271. var len = orig.length;
  27272. var copy = [];
  27273. for (var i = 0; i < len; i++) {
  27274. copy.push(orig[i]);
  27275. }
  27276. return copy;
  27277. }
  27278. };
  27279. Geometry.prototype.getVertexBuffer = function (kind) {
  27280. if (!this.isReady()) {
  27281. return null;
  27282. }
  27283. return this._vertexBuffers[kind];
  27284. };
  27285. Geometry.prototype.getVertexBuffers = function () {
  27286. if (!this.isReady()) {
  27287. return null;
  27288. }
  27289. return this._vertexBuffers;
  27290. };
  27291. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27292. if (!this._vertexBuffers) {
  27293. if (this._delayInfo) {
  27294. return this._delayInfo.indexOf(kind) !== -1;
  27295. }
  27296. return false;
  27297. }
  27298. return this._vertexBuffers[kind] !== undefined;
  27299. };
  27300. Geometry.prototype.getVerticesDataKinds = function () {
  27301. var result = [];
  27302. var kind;
  27303. if (!this._vertexBuffers && this._delayInfo) {
  27304. for (kind in this._delayInfo) {
  27305. result.push(kind);
  27306. }
  27307. }
  27308. else {
  27309. for (kind in this._vertexBuffers) {
  27310. result.push(kind);
  27311. }
  27312. }
  27313. return result;
  27314. };
  27315. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27316. if (this._indexBuffer) {
  27317. this._engine._releaseBuffer(this._indexBuffer);
  27318. }
  27319. this._disposeVertexArrayObjects();
  27320. this._indices = indices;
  27321. if (this._meshes.length !== 0 && this._indices) {
  27322. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27323. }
  27324. if (totalVertices !== undefined) {
  27325. this._totalVertices = totalVertices;
  27326. }
  27327. var meshes = this._meshes;
  27328. var numOfMeshes = meshes.length;
  27329. for (var index = 0; index < numOfMeshes; index++) {
  27330. meshes[index]._createGlobalSubMesh();
  27331. }
  27332. this.notifyUpdate();
  27333. };
  27334. Geometry.prototype.getTotalIndices = function () {
  27335. if (!this.isReady()) {
  27336. return 0;
  27337. }
  27338. return this._indices.length;
  27339. };
  27340. Geometry.prototype.getIndices = function (copyWhenShared) {
  27341. if (!this.isReady()) {
  27342. return null;
  27343. }
  27344. var orig = this._indices;
  27345. if (!copyWhenShared || this._meshes.length === 1) {
  27346. return orig;
  27347. }
  27348. else {
  27349. var len = orig.length;
  27350. var copy = [];
  27351. for (var i = 0; i < len; i++) {
  27352. copy.push(orig[i]);
  27353. }
  27354. return copy;
  27355. }
  27356. };
  27357. Geometry.prototype.getIndexBuffer = function () {
  27358. if (!this.isReady()) {
  27359. return null;
  27360. }
  27361. return this._indexBuffer;
  27362. };
  27363. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27364. if (!effect || !this._vertexArrayObjects) {
  27365. return;
  27366. }
  27367. if (this._vertexArrayObjects[effect.key]) {
  27368. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27369. delete this._vertexArrayObjects[effect.key];
  27370. }
  27371. };
  27372. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27373. var meshes = this._meshes;
  27374. var index = meshes.indexOf(mesh);
  27375. if (index === -1) {
  27376. return;
  27377. }
  27378. meshes.splice(index, 1);
  27379. mesh._geometry = null;
  27380. if (meshes.length === 0 && shouldDispose) {
  27381. this.dispose();
  27382. }
  27383. };
  27384. Geometry.prototype.applyToMesh = function (mesh) {
  27385. if (mesh._geometry === this) {
  27386. return;
  27387. }
  27388. var previousGeometry = mesh._geometry;
  27389. if (previousGeometry) {
  27390. previousGeometry.releaseForMesh(mesh);
  27391. }
  27392. var meshes = this._meshes;
  27393. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27394. mesh._geometry = this;
  27395. this._scene.pushGeometry(this);
  27396. meshes.push(mesh);
  27397. if (this.isReady()) {
  27398. this._applyToMesh(mesh);
  27399. }
  27400. else {
  27401. mesh._boundingInfo = this._boundingInfo;
  27402. }
  27403. };
  27404. Geometry.prototype.updateExtend = function (data, stride) {
  27405. if (data === void 0) { data = null; }
  27406. if (!data) {
  27407. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27408. }
  27409. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27410. };
  27411. Geometry.prototype._applyToMesh = function (mesh) {
  27412. var numOfMeshes = this._meshes.length;
  27413. // vertexBuffers
  27414. for (var kind in this._vertexBuffers) {
  27415. if (numOfMeshes === 1) {
  27416. this._vertexBuffers[kind].create();
  27417. }
  27418. var buffer = this._vertexBuffers[kind].getBuffer();
  27419. if (buffer)
  27420. buffer.references = numOfMeshes;
  27421. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27422. if (!this._extend) {
  27423. this.updateExtend(this._vertexBuffers[kind].getData());
  27424. }
  27425. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27426. mesh._createGlobalSubMesh();
  27427. //bounding info was just created again, world matrix should be applied again.
  27428. mesh._updateBoundingInfo();
  27429. }
  27430. }
  27431. // indexBuffer
  27432. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27433. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27434. }
  27435. if (this._indexBuffer) {
  27436. this._indexBuffer.references = numOfMeshes;
  27437. }
  27438. };
  27439. Geometry.prototype.notifyUpdate = function (kind) {
  27440. if (this.onGeometryUpdated) {
  27441. this.onGeometryUpdated(this, kind);
  27442. }
  27443. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27444. var mesh = _a[_i];
  27445. mesh._markSubMeshesAsAttributesDirty();
  27446. }
  27447. };
  27448. Geometry.prototype.load = function (scene, onLoaded) {
  27449. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27450. return;
  27451. }
  27452. if (this.isReady()) {
  27453. if (onLoaded) {
  27454. onLoaded();
  27455. }
  27456. return;
  27457. }
  27458. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27459. this._queueLoad(scene, onLoaded);
  27460. };
  27461. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27462. var _this = this;
  27463. scene._addPendingData(this);
  27464. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27465. _this._delayLoadingFunction(JSON.parse(data), _this);
  27466. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27467. _this._delayInfo = [];
  27468. scene._removePendingData(_this);
  27469. var meshes = _this._meshes;
  27470. var numOfMeshes = meshes.length;
  27471. for (var index = 0; index < numOfMeshes; index++) {
  27472. _this._applyToMesh(meshes[index]);
  27473. }
  27474. if (onLoaded) {
  27475. onLoaded();
  27476. }
  27477. }, function () { }, scene.database);
  27478. };
  27479. /**
  27480. * Invert the geometry to move from a right handed system to a left handed one.
  27481. */
  27482. Geometry.prototype.toLeftHanded = function () {
  27483. // Flip faces
  27484. var tIndices = this.getIndices(false);
  27485. if (tIndices != null && tIndices.length > 0) {
  27486. for (var i = 0; i < tIndices.length; i += 3) {
  27487. var tTemp = tIndices[i + 0];
  27488. tIndices[i + 0] = tIndices[i + 2];
  27489. tIndices[i + 2] = tTemp;
  27490. }
  27491. this.setIndices(tIndices);
  27492. }
  27493. // Negate position.z
  27494. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27495. if (tPositions != null && tPositions.length > 0) {
  27496. for (var i = 0; i < tPositions.length; i += 3) {
  27497. tPositions[i + 2] = -tPositions[i + 2];
  27498. }
  27499. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27500. }
  27501. // Negate normal.z
  27502. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27503. if (tNormals != null && tNormals.length > 0) {
  27504. for (var i = 0; i < tNormals.length; i += 3) {
  27505. tNormals[i + 2] = -tNormals[i + 2];
  27506. }
  27507. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27508. }
  27509. };
  27510. // Cache
  27511. Geometry.prototype._resetPointsArrayCache = function () {
  27512. this._positions = null;
  27513. };
  27514. Geometry.prototype._generatePointsArray = function () {
  27515. if (this._positions)
  27516. return true;
  27517. this._positions = [];
  27518. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27519. if (!data) {
  27520. return false;
  27521. }
  27522. for (var index = 0; index < data.length; index += 3) {
  27523. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27524. }
  27525. return true;
  27526. };
  27527. Geometry.prototype.isDisposed = function () {
  27528. return this._isDisposed;
  27529. };
  27530. Geometry.prototype._disposeVertexArrayObjects = function () {
  27531. if (this._vertexArrayObjects) {
  27532. for (var kind in this._vertexArrayObjects) {
  27533. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27534. }
  27535. this._vertexArrayObjects = {};
  27536. }
  27537. };
  27538. Geometry.prototype.dispose = function () {
  27539. var meshes = this._meshes;
  27540. var numOfMeshes = meshes.length;
  27541. var index;
  27542. for (index = 0; index < numOfMeshes; index++) {
  27543. this.releaseForMesh(meshes[index]);
  27544. }
  27545. this._meshes = [];
  27546. this._disposeVertexArrayObjects();
  27547. for (var kind in this._vertexBuffers) {
  27548. this._vertexBuffers[kind].dispose();
  27549. }
  27550. this._vertexBuffers = {};
  27551. this._totalVertices = 0;
  27552. if (this._indexBuffer) {
  27553. this._engine._releaseBuffer(this._indexBuffer);
  27554. }
  27555. this._indexBuffer = null;
  27556. this._indices = [];
  27557. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27558. this.delayLoadingFile = null;
  27559. this._delayLoadingFunction = null;
  27560. this._delayInfo = [];
  27561. this._boundingInfo = null;
  27562. this._scene.removeGeometry(this);
  27563. this._isDisposed = true;
  27564. };
  27565. Geometry.prototype.copy = function (id) {
  27566. var vertexData = new BABYLON.VertexData();
  27567. vertexData.indices = [];
  27568. var indices = this.getIndices();
  27569. for (var index = 0; index < indices.length; index++) {
  27570. vertexData.indices.push(indices[index]);
  27571. }
  27572. var updatable = false;
  27573. var stopChecking = false;
  27574. var kind;
  27575. for (kind in this._vertexBuffers) {
  27576. // using slice() to make a copy of the array and not just reference it
  27577. var data = this.getVerticesData(kind);
  27578. if (data instanceof Float32Array) {
  27579. vertexData.set(new Float32Array(data), kind);
  27580. }
  27581. else {
  27582. vertexData.set(data.slice(0), kind);
  27583. }
  27584. if (!stopChecking) {
  27585. updatable = this.getVertexBuffer(kind).isUpdatable();
  27586. stopChecking = !updatable;
  27587. }
  27588. }
  27589. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27590. geometry.delayLoadState = this.delayLoadState;
  27591. geometry.delayLoadingFile = this.delayLoadingFile;
  27592. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27593. for (kind in this._delayInfo) {
  27594. geometry._delayInfo = geometry._delayInfo || [];
  27595. geometry._delayInfo.push(kind);
  27596. }
  27597. // Bounding info
  27598. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27599. return geometry;
  27600. };
  27601. Geometry.prototype.serialize = function () {
  27602. var serializationObject = {};
  27603. serializationObject.id = this.id;
  27604. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27605. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27606. }
  27607. return serializationObject;
  27608. };
  27609. Geometry.prototype.toNumberArray = function (origin) {
  27610. if (Array.isArray(origin)) {
  27611. return origin;
  27612. }
  27613. else {
  27614. return Array.prototype.slice.call(origin);
  27615. }
  27616. };
  27617. Geometry.prototype.serializeVerticeData = function () {
  27618. var serializationObject = this.serialize();
  27619. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27620. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27621. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27622. serializationObject.positions._updatable = true;
  27623. }
  27624. }
  27625. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27626. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27627. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27628. serializationObject.normals._updatable = true;
  27629. }
  27630. }
  27631. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27632. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27633. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27634. serializationObject.uvs._updatable = true;
  27635. }
  27636. }
  27637. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27638. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27639. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27640. serializationObject.uv2s._updatable = true;
  27641. }
  27642. }
  27643. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27644. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27645. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27646. serializationObject.uv3s._updatable = true;
  27647. }
  27648. }
  27649. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27650. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27651. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27652. serializationObject.uv4s._updatable = true;
  27653. }
  27654. }
  27655. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27656. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27657. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27658. serializationObject.uv5s._updatable = true;
  27659. }
  27660. }
  27661. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27662. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27663. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27664. serializationObject.uv6s._updatable = true;
  27665. }
  27666. }
  27667. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27668. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27669. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27670. serializationObject.colors._updatable = true;
  27671. }
  27672. }
  27673. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27674. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27675. serializationObject.matricesIndices._isExpanded = true;
  27676. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27677. serializationObject.matricesIndices._updatable = true;
  27678. }
  27679. }
  27680. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27681. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27682. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27683. serializationObject.matricesWeights._updatable = true;
  27684. }
  27685. }
  27686. serializationObject.indices = this.toNumberArray(this.getIndices());
  27687. return serializationObject;
  27688. };
  27689. // Statics
  27690. Geometry.ExtractFromMesh = function (mesh, id) {
  27691. var geometry = mesh._geometry;
  27692. if (!geometry) {
  27693. return null;
  27694. }
  27695. return geometry.copy(id);
  27696. };
  27697. /**
  27698. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27699. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27700. * Be aware Math.random() could cause collisions, but:
  27701. * "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"
  27702. */
  27703. Geometry.RandomId = function () {
  27704. return BABYLON.Tools.RandomId();
  27705. };
  27706. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27707. var scene = mesh.getScene();
  27708. // Geometry
  27709. var geometryId = parsedGeometry.geometryId;
  27710. if (geometryId) {
  27711. var geometry = scene.getGeometryByID(geometryId);
  27712. if (geometry) {
  27713. geometry.applyToMesh(mesh);
  27714. }
  27715. }
  27716. else if (parsedGeometry instanceof ArrayBuffer) {
  27717. var binaryInfo = mesh._binaryInfo;
  27718. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27719. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27720. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27721. }
  27722. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27723. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27724. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27725. }
  27726. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27727. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27728. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27729. }
  27730. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27731. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27732. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27733. }
  27734. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27735. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27736. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27737. }
  27738. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27739. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27740. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27741. }
  27742. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27743. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27744. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27745. }
  27746. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27747. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27748. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27749. }
  27750. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27751. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27752. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27753. }
  27754. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27755. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27756. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27757. }
  27758. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27759. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27760. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27761. }
  27762. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27763. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27764. mesh.setIndices(indicesData);
  27765. }
  27766. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27767. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27768. mesh.subMeshes = [];
  27769. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27770. var materialIndex = subMeshesData[(i * 5) + 0];
  27771. var verticesStart = subMeshesData[(i * 5) + 1];
  27772. var verticesCount = subMeshesData[(i * 5) + 2];
  27773. var indexStart = subMeshesData[(i * 5) + 3];
  27774. var indexCount = subMeshesData[(i * 5) + 4];
  27775. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27776. }
  27777. }
  27778. }
  27779. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27780. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27781. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27782. if (parsedGeometry.uvs) {
  27783. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27784. }
  27785. if (parsedGeometry.uvs2) {
  27786. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27787. }
  27788. if (parsedGeometry.uvs3) {
  27789. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27790. }
  27791. if (parsedGeometry.uvs4) {
  27792. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27793. }
  27794. if (parsedGeometry.uvs5) {
  27795. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27796. }
  27797. if (parsedGeometry.uvs6) {
  27798. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27799. }
  27800. if (parsedGeometry.colors) {
  27801. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27802. }
  27803. if (parsedGeometry.matricesIndices) {
  27804. if (!parsedGeometry.matricesIndices._isExpanded) {
  27805. var floatIndices = [];
  27806. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27807. var matricesIndex = parsedGeometry.matricesIndices[i];
  27808. floatIndices.push(matricesIndex & 0x000000FF);
  27809. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27810. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27811. floatIndices.push(matricesIndex >> 24);
  27812. }
  27813. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27814. }
  27815. else {
  27816. delete parsedGeometry.matricesIndices._isExpanded;
  27817. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27818. }
  27819. }
  27820. if (parsedGeometry.matricesIndicesExtra) {
  27821. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27822. var floatIndices = [];
  27823. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27824. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27825. floatIndices.push(matricesIndex & 0x000000FF);
  27826. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27827. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27828. floatIndices.push(matricesIndex >> 24);
  27829. }
  27830. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27831. }
  27832. else {
  27833. delete parsedGeometry.matricesIndices._isExpanded;
  27834. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27835. }
  27836. }
  27837. if (parsedGeometry.matricesWeights) {
  27838. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27839. }
  27840. if (parsedGeometry.matricesWeightsExtra) {
  27841. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27842. }
  27843. mesh.setIndices(parsedGeometry.indices);
  27844. }
  27845. // SubMeshes
  27846. if (parsedGeometry.subMeshes) {
  27847. mesh.subMeshes = [];
  27848. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27849. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27850. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27851. }
  27852. }
  27853. // Flat shading
  27854. if (mesh._shouldGenerateFlatShading) {
  27855. mesh.convertToFlatShadedMesh();
  27856. delete mesh._shouldGenerateFlatShading;
  27857. }
  27858. // Update
  27859. mesh.computeWorldMatrix(true);
  27860. // Octree
  27861. if (scene['_selectionOctree']) {
  27862. scene['_selectionOctree'].addMesh(mesh);
  27863. }
  27864. };
  27865. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27866. if (scene.getGeometryByID(parsedVertexData.id)) {
  27867. return null; // null since geometry could be something else than a box...
  27868. }
  27869. var geometry = new Geometry(parsedVertexData.id, scene);
  27870. if (BABYLON.Tags) {
  27871. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27872. }
  27873. if (parsedVertexData.delayLoadingFile) {
  27874. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27875. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27876. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27877. geometry._delayInfo = [];
  27878. if (parsedVertexData.hasUVs) {
  27879. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27880. }
  27881. if (parsedVertexData.hasUVs2) {
  27882. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27883. }
  27884. if (parsedVertexData.hasUVs3) {
  27885. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27886. }
  27887. if (parsedVertexData.hasUVs4) {
  27888. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27889. }
  27890. if (parsedVertexData.hasUVs5) {
  27891. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27892. }
  27893. if (parsedVertexData.hasUVs6) {
  27894. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27895. }
  27896. if (parsedVertexData.hasColors) {
  27897. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27898. }
  27899. if (parsedVertexData.hasMatricesIndices) {
  27900. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27901. }
  27902. if (parsedVertexData.hasMatricesWeights) {
  27903. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27904. }
  27905. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27906. }
  27907. else {
  27908. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27909. }
  27910. scene.pushGeometry(geometry, true);
  27911. return geometry;
  27912. };
  27913. return Geometry;
  27914. }());
  27915. BABYLON.Geometry = Geometry;
  27916. /////// Primitives //////////////////////////////////////////////
  27917. (function (Geometry) {
  27918. var Primitives;
  27919. (function (Primitives) {
  27920. /// Abstract class
  27921. var _Primitive = (function (_super) {
  27922. __extends(_Primitive, _super);
  27923. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27924. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27925. _this._canBeRegenerated = _canBeRegenerated;
  27926. _this._beingRegenerated = true;
  27927. _this.regenerate();
  27928. _this._beingRegenerated = false;
  27929. return _this;
  27930. }
  27931. _Primitive.prototype.canBeRegenerated = function () {
  27932. return this._canBeRegenerated;
  27933. };
  27934. _Primitive.prototype.regenerate = function () {
  27935. if (!this._canBeRegenerated) {
  27936. return;
  27937. }
  27938. this._beingRegenerated = true;
  27939. this.setAllVerticesData(this._regenerateVertexData(), false);
  27940. this._beingRegenerated = false;
  27941. };
  27942. _Primitive.prototype.asNewGeometry = function (id) {
  27943. return _super.prototype.copy.call(this, id);
  27944. };
  27945. // overrides
  27946. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27947. if (!this._beingRegenerated) {
  27948. return;
  27949. }
  27950. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27951. };
  27952. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27953. if (!this._beingRegenerated) {
  27954. return;
  27955. }
  27956. _super.prototype.setVerticesData.call(this, kind, data, false);
  27957. };
  27958. // to override
  27959. // protected
  27960. _Primitive.prototype._regenerateVertexData = function () {
  27961. throw new Error("Abstract method");
  27962. };
  27963. _Primitive.prototype.copy = function (id) {
  27964. throw new Error("Must be overriden in sub-classes.");
  27965. };
  27966. _Primitive.prototype.serialize = function () {
  27967. var serializationObject = _super.prototype.serialize.call(this);
  27968. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27969. return serializationObject;
  27970. };
  27971. return _Primitive;
  27972. }(Geometry));
  27973. Primitives._Primitive = _Primitive;
  27974. var Ribbon = (function (_super) {
  27975. __extends(Ribbon, _super);
  27976. // Members
  27977. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27978. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27979. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27980. _this.pathArray = pathArray;
  27981. _this.closeArray = closeArray;
  27982. _this.closePath = closePath;
  27983. _this.offset = offset;
  27984. _this.side = side;
  27985. return _this;
  27986. }
  27987. Ribbon.prototype._regenerateVertexData = function () {
  27988. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27989. };
  27990. Ribbon.prototype.copy = function (id) {
  27991. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27992. };
  27993. return Ribbon;
  27994. }(_Primitive));
  27995. Primitives.Ribbon = Ribbon;
  27996. var Box = (function (_super) {
  27997. __extends(Box, _super);
  27998. // Members
  27999. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28000. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28001. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28002. _this.size = size;
  28003. _this.side = side;
  28004. return _this;
  28005. }
  28006. Box.prototype._regenerateVertexData = function () {
  28007. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28008. };
  28009. Box.prototype.copy = function (id) {
  28010. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28011. };
  28012. Box.prototype.serialize = function () {
  28013. var serializationObject = _super.prototype.serialize.call(this);
  28014. serializationObject.size = this.size;
  28015. return serializationObject;
  28016. };
  28017. Box.Parse = function (parsedBox, scene) {
  28018. if (scene.getGeometryByID(parsedBox.id)) {
  28019. return null; // null since geometry could be something else than a box...
  28020. }
  28021. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28022. if (BABYLON.Tags) {
  28023. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28024. }
  28025. scene.pushGeometry(box, true);
  28026. return box;
  28027. };
  28028. return Box;
  28029. }(_Primitive));
  28030. Primitives.Box = Box;
  28031. var Sphere = (function (_super) {
  28032. __extends(Sphere, _super);
  28033. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28034. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28035. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28036. _this.segments = segments;
  28037. _this.diameter = diameter;
  28038. _this.side = side;
  28039. return _this;
  28040. }
  28041. Sphere.prototype._regenerateVertexData = function () {
  28042. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28043. };
  28044. Sphere.prototype.copy = function (id) {
  28045. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28046. };
  28047. Sphere.prototype.serialize = function () {
  28048. var serializationObject = _super.prototype.serialize.call(this);
  28049. serializationObject.segments = this.segments;
  28050. serializationObject.diameter = this.diameter;
  28051. return serializationObject;
  28052. };
  28053. Sphere.Parse = function (parsedSphere, scene) {
  28054. if (scene.getGeometryByID(parsedSphere.id)) {
  28055. return null; // null since geometry could be something else than a sphere...
  28056. }
  28057. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28058. if (BABYLON.Tags) {
  28059. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28060. }
  28061. scene.pushGeometry(sphere, true);
  28062. return sphere;
  28063. };
  28064. return Sphere;
  28065. }(_Primitive));
  28066. Primitives.Sphere = Sphere;
  28067. var Disc = (function (_super) {
  28068. __extends(Disc, _super);
  28069. // Members
  28070. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28071. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28072. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28073. _this.radius = radius;
  28074. _this.tessellation = tessellation;
  28075. _this.side = side;
  28076. return _this;
  28077. }
  28078. Disc.prototype._regenerateVertexData = function () {
  28079. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28080. };
  28081. Disc.prototype.copy = function (id) {
  28082. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28083. };
  28084. return Disc;
  28085. }(_Primitive));
  28086. Primitives.Disc = Disc;
  28087. var Cylinder = (function (_super) {
  28088. __extends(Cylinder, _super);
  28089. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28090. if (subdivisions === void 0) { subdivisions = 1; }
  28091. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28092. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28093. _this.height = height;
  28094. _this.diameterTop = diameterTop;
  28095. _this.diameterBottom = diameterBottom;
  28096. _this.tessellation = tessellation;
  28097. _this.subdivisions = subdivisions;
  28098. _this.side = side;
  28099. return _this;
  28100. }
  28101. Cylinder.prototype._regenerateVertexData = function () {
  28102. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28103. };
  28104. Cylinder.prototype.copy = function (id) {
  28105. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28106. };
  28107. Cylinder.prototype.serialize = function () {
  28108. var serializationObject = _super.prototype.serialize.call(this);
  28109. serializationObject.height = this.height;
  28110. serializationObject.diameterTop = this.diameterTop;
  28111. serializationObject.diameterBottom = this.diameterBottom;
  28112. serializationObject.tessellation = this.tessellation;
  28113. return serializationObject;
  28114. };
  28115. Cylinder.Parse = function (parsedCylinder, scene) {
  28116. if (scene.getGeometryByID(parsedCylinder.id)) {
  28117. return null; // null since geometry could be something else than a cylinder...
  28118. }
  28119. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28120. if (BABYLON.Tags) {
  28121. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28122. }
  28123. scene.pushGeometry(cylinder, true);
  28124. return cylinder;
  28125. };
  28126. return Cylinder;
  28127. }(_Primitive));
  28128. Primitives.Cylinder = Cylinder;
  28129. var Torus = (function (_super) {
  28130. __extends(Torus, _super);
  28131. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28132. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28133. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28134. _this.diameter = diameter;
  28135. _this.thickness = thickness;
  28136. _this.tessellation = tessellation;
  28137. _this.side = side;
  28138. return _this;
  28139. }
  28140. Torus.prototype._regenerateVertexData = function () {
  28141. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28142. };
  28143. Torus.prototype.copy = function (id) {
  28144. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28145. };
  28146. Torus.prototype.serialize = function () {
  28147. var serializationObject = _super.prototype.serialize.call(this);
  28148. serializationObject.diameter = this.diameter;
  28149. serializationObject.thickness = this.thickness;
  28150. serializationObject.tessellation = this.tessellation;
  28151. return serializationObject;
  28152. };
  28153. Torus.Parse = function (parsedTorus, scene) {
  28154. if (scene.getGeometryByID(parsedTorus.id)) {
  28155. return null; // null since geometry could be something else than a torus...
  28156. }
  28157. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28158. if (BABYLON.Tags) {
  28159. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28160. }
  28161. scene.pushGeometry(torus, true);
  28162. return torus;
  28163. };
  28164. return Torus;
  28165. }(_Primitive));
  28166. Primitives.Torus = Torus;
  28167. var Ground = (function (_super) {
  28168. __extends(Ground, _super);
  28169. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28170. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28171. _this.width = width;
  28172. _this.height = height;
  28173. _this.subdivisions = subdivisions;
  28174. return _this;
  28175. }
  28176. Ground.prototype._regenerateVertexData = function () {
  28177. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28178. };
  28179. Ground.prototype.copy = function (id) {
  28180. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28181. };
  28182. Ground.prototype.serialize = function () {
  28183. var serializationObject = _super.prototype.serialize.call(this);
  28184. serializationObject.width = this.width;
  28185. serializationObject.height = this.height;
  28186. serializationObject.subdivisions = this.subdivisions;
  28187. return serializationObject;
  28188. };
  28189. Ground.Parse = function (parsedGround, scene) {
  28190. if (scene.getGeometryByID(parsedGround.id)) {
  28191. return null; // null since geometry could be something else than a ground...
  28192. }
  28193. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28194. if (BABYLON.Tags) {
  28195. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28196. }
  28197. scene.pushGeometry(ground, true);
  28198. return ground;
  28199. };
  28200. return Ground;
  28201. }(_Primitive));
  28202. Primitives.Ground = Ground;
  28203. var TiledGround = (function (_super) {
  28204. __extends(TiledGround, _super);
  28205. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28206. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28207. _this.xmin = xmin;
  28208. _this.zmin = zmin;
  28209. _this.xmax = xmax;
  28210. _this.zmax = zmax;
  28211. _this.subdivisions = subdivisions;
  28212. _this.precision = precision;
  28213. return _this;
  28214. }
  28215. TiledGround.prototype._regenerateVertexData = function () {
  28216. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28217. };
  28218. TiledGround.prototype.copy = function (id) {
  28219. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28220. };
  28221. return TiledGround;
  28222. }(_Primitive));
  28223. Primitives.TiledGround = TiledGround;
  28224. var Plane = (function (_super) {
  28225. __extends(Plane, _super);
  28226. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28227. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28228. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28229. _this.size = size;
  28230. _this.side = side;
  28231. return _this;
  28232. }
  28233. Plane.prototype._regenerateVertexData = function () {
  28234. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28235. };
  28236. Plane.prototype.copy = function (id) {
  28237. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28238. };
  28239. Plane.prototype.serialize = function () {
  28240. var serializationObject = _super.prototype.serialize.call(this);
  28241. serializationObject.size = this.size;
  28242. return serializationObject;
  28243. };
  28244. Plane.Parse = function (parsedPlane, scene) {
  28245. if (scene.getGeometryByID(parsedPlane.id)) {
  28246. return null; // null since geometry could be something else than a ground...
  28247. }
  28248. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28249. if (BABYLON.Tags) {
  28250. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28251. }
  28252. scene.pushGeometry(plane, true);
  28253. return plane;
  28254. };
  28255. return Plane;
  28256. }(_Primitive));
  28257. Primitives.Plane = Plane;
  28258. var TorusKnot = (function (_super) {
  28259. __extends(TorusKnot, _super);
  28260. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28261. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28262. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28263. _this.radius = radius;
  28264. _this.tube = tube;
  28265. _this.radialSegments = radialSegments;
  28266. _this.tubularSegments = tubularSegments;
  28267. _this.p = p;
  28268. _this.q = q;
  28269. _this.side = side;
  28270. return _this;
  28271. }
  28272. TorusKnot.prototype._regenerateVertexData = function () {
  28273. 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 });
  28274. };
  28275. TorusKnot.prototype.copy = function (id) {
  28276. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28277. };
  28278. TorusKnot.prototype.serialize = function () {
  28279. var serializationObject = _super.prototype.serialize.call(this);
  28280. serializationObject.radius = this.radius;
  28281. serializationObject.tube = this.tube;
  28282. serializationObject.radialSegments = this.radialSegments;
  28283. serializationObject.tubularSegments = this.tubularSegments;
  28284. serializationObject.p = this.p;
  28285. serializationObject.q = this.q;
  28286. return serializationObject;
  28287. };
  28288. ;
  28289. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28290. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28291. return null; // null since geometry could be something else than a ground...
  28292. }
  28293. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28294. if (BABYLON.Tags) {
  28295. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28296. }
  28297. scene.pushGeometry(torusKnot, true);
  28298. return torusKnot;
  28299. };
  28300. return TorusKnot;
  28301. }(_Primitive));
  28302. Primitives.TorusKnot = TorusKnot;
  28303. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28304. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28305. })(BABYLON || (BABYLON = {}));
  28306. //# sourceMappingURL=babylon.geometry.js.map
  28307. var BABYLON;
  28308. (function (BABYLON) {
  28309. var PostProcessManager = (function () {
  28310. function PostProcessManager(scene) {
  28311. this._vertexBuffers = {};
  28312. this._scene = scene;
  28313. }
  28314. PostProcessManager.prototype._prepareBuffers = function () {
  28315. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28316. return;
  28317. }
  28318. // VBO
  28319. var vertices = [];
  28320. vertices.push(1, 1);
  28321. vertices.push(-1, 1);
  28322. vertices.push(-1, -1);
  28323. vertices.push(1, -1);
  28324. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28325. // Indices
  28326. var indices = [];
  28327. indices.push(0);
  28328. indices.push(1);
  28329. indices.push(2);
  28330. indices.push(0);
  28331. indices.push(2);
  28332. indices.push(3);
  28333. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28334. };
  28335. // Methods
  28336. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  28337. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28338. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28339. return false;
  28340. }
  28341. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  28342. return true;
  28343. };
  28344. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28345. var engine = this._scene.getEngine();
  28346. for (var index = 0; index < postProcesses.length; index++) {
  28347. if (index < postProcesses.length - 1) {
  28348. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28349. }
  28350. else {
  28351. if (targetTexture) {
  28352. engine.bindFramebuffer(targetTexture);
  28353. }
  28354. else {
  28355. engine.restoreDefaultFramebuffer();
  28356. }
  28357. }
  28358. var pp = postProcesses[index];
  28359. var effect = pp.apply();
  28360. if (effect) {
  28361. pp.onBeforeRenderObservable.notifyObservers(effect);
  28362. // VBOs
  28363. this._prepareBuffers();
  28364. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28365. // Draw order
  28366. engine.draw(true, 0, 6);
  28367. pp.onAfterRenderObservable.notifyObservers(effect);
  28368. }
  28369. }
  28370. // Restore depth buffer
  28371. engine.setDepthBuffer(true);
  28372. engine.setDepthWrite(true);
  28373. };
  28374. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28375. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28376. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28377. return;
  28378. }
  28379. var engine = this._scene.getEngine();
  28380. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28381. if (index < len - 1) {
  28382. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28383. }
  28384. else {
  28385. if (targetTexture) {
  28386. engine.bindFramebuffer(targetTexture, faceIndex);
  28387. }
  28388. else {
  28389. engine.restoreDefaultFramebuffer();
  28390. }
  28391. }
  28392. if (doNotPresent) {
  28393. break;
  28394. }
  28395. var pp = postProcesses[index];
  28396. var effect = pp.apply();
  28397. if (effect) {
  28398. pp.onBeforeRenderObservable.notifyObservers(effect);
  28399. // VBOs
  28400. this._prepareBuffers();
  28401. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28402. // Draw order
  28403. engine.draw(true, 0, 6);
  28404. pp.onAfterRenderObservable.notifyObservers(effect);
  28405. }
  28406. }
  28407. // Restore states
  28408. engine.setDepthBuffer(true);
  28409. engine.setDepthWrite(true);
  28410. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28411. };
  28412. PostProcessManager.prototype.dispose = function () {
  28413. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28414. if (buffer) {
  28415. buffer.dispose();
  28416. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28417. }
  28418. if (this._indexBuffer) {
  28419. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28420. this._indexBuffer = null;
  28421. }
  28422. };
  28423. return PostProcessManager;
  28424. }());
  28425. BABYLON.PostProcessManager = PostProcessManager;
  28426. })(BABYLON || (BABYLON = {}));
  28427. //# sourceMappingURL=babylon.postProcessManager.js.map
  28428. var BABYLON;
  28429. (function (BABYLON) {
  28430. var StandardMaterialDefines = (function (_super) {
  28431. __extends(StandardMaterialDefines, _super);
  28432. function StandardMaterialDefines() {
  28433. var _this = _super.call(this) || this;
  28434. _this.DIFFUSE = false;
  28435. _this.AMBIENT = false;
  28436. _this.OPACITY = false;
  28437. _this.OPACITYRGB = false;
  28438. _this.REFLECTION = false;
  28439. _this.EMISSIVE = false;
  28440. _this.SPECULAR = false;
  28441. _this.BUMP = false;
  28442. _this.PARALLAX = false;
  28443. _this.PARALLAXOCCLUSION = false;
  28444. _this.SPECULAROVERALPHA = false;
  28445. _this.CLIPPLANE = false;
  28446. _this.ALPHATEST = false;
  28447. _this.ALPHAFROMDIFFUSE = false;
  28448. _this.POINTSIZE = false;
  28449. _this.FOG = false;
  28450. _this.SPECULARTERM = false;
  28451. _this.DIFFUSEFRESNEL = false;
  28452. _this.OPACITYFRESNEL = false;
  28453. _this.REFLECTIONFRESNEL = false;
  28454. _this.REFRACTIONFRESNEL = false;
  28455. _this.EMISSIVEFRESNEL = false;
  28456. _this.FRESNEL = false;
  28457. _this.NORMAL = false;
  28458. _this.UV1 = false;
  28459. _this.UV2 = false;
  28460. _this.VERTEXCOLOR = false;
  28461. _this.VERTEXALPHA = false;
  28462. _this.NUM_BONE_INFLUENCERS = 0;
  28463. _this.BonesPerMesh = 0;
  28464. _this.INSTANCES = false;
  28465. _this.GLOSSINESS = false;
  28466. _this.ROUGHNESS = false;
  28467. _this.EMISSIVEASILLUMINATION = false;
  28468. _this.LINKEMISSIVEWITHDIFFUSE = false;
  28469. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  28470. _this.LIGHTMAP = false;
  28471. _this.USELIGHTMAPASSHADOWMAP = false;
  28472. _this.REFLECTIONMAP_3D = false;
  28473. _this.REFLECTIONMAP_SPHERICAL = false;
  28474. _this.REFLECTIONMAP_PLANAR = false;
  28475. _this.REFLECTIONMAP_CUBIC = false;
  28476. _this.REFLECTIONMAP_PROJECTION = false;
  28477. _this.REFLECTIONMAP_SKYBOX = false;
  28478. _this.REFLECTIONMAP_EXPLICIT = false;
  28479. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  28480. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  28481. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  28482. _this.INVERTCUBICMAP = false;
  28483. _this.LOGARITHMICDEPTH = false;
  28484. _this.REFRACTION = false;
  28485. _this.REFRACTIONMAP_3D = false;
  28486. _this.REFLECTIONOVERALPHA = false;
  28487. _this.INVERTNORMALMAPX = false;
  28488. _this.INVERTNORMALMAPY = false;
  28489. _this.TWOSIDEDLIGHTING = false;
  28490. _this.SHADOWFLOAT = false;
  28491. _this.MORPHTARGETS = false;
  28492. _this.MORPHTARGETS_NORMAL = false;
  28493. _this.MORPHTARGETS_TANGENT = false;
  28494. _this.NUM_MORPH_INFLUENCERS = 0;
  28495. _this.USERIGHTHANDEDSYSTEM = false;
  28496. _this.IMAGEPROCESSING = false;
  28497. _this.VIGNETTE = false;
  28498. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  28499. _this.VIGNETTEBLENDMODEOPAQUE = false;
  28500. _this.TONEMAPPING = false;
  28501. _this.CONTRAST = false;
  28502. _this.COLORCURVES = false;
  28503. _this.COLORGRADING = false;
  28504. _this.SAMPLER3DGREENDEPTH = false;
  28505. _this.SAMPLER3DBGRMAP = false;
  28506. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  28507. _this.EXPOSURE = false;
  28508. _this.rebuild();
  28509. return _this;
  28510. }
  28511. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  28512. var modes = [
  28513. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  28514. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  28515. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  28516. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  28517. ];
  28518. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  28519. var mode = modes_1[_i];
  28520. this[mode] = (mode === modeToEnable);
  28521. }
  28522. };
  28523. return StandardMaterialDefines;
  28524. }(BABYLON.MaterialDefines));
  28525. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  28526. var StandardMaterial = (function (_super) {
  28527. __extends(StandardMaterial, _super);
  28528. function StandardMaterial(name, scene) {
  28529. var _this = _super.call(this, name, scene) || this;
  28530. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  28531. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  28532. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  28533. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  28534. _this.specularPower = 64;
  28535. _this._useAlphaFromDiffuseTexture = false;
  28536. _this._useEmissiveAsIllumination = false;
  28537. _this._linkEmissiveWithDiffuse = false;
  28538. _this._useSpecularOverAlpha = false;
  28539. _this._useReflectionOverAlpha = false;
  28540. _this._disableLighting = false;
  28541. _this._useParallax = false;
  28542. _this._useParallaxOcclusion = false;
  28543. _this.parallaxScaleBias = 0.05;
  28544. _this._roughness = 0;
  28545. _this.indexOfRefraction = 0.98;
  28546. _this.invertRefractionY = true;
  28547. _this._useLightmapAsShadowmap = false;
  28548. _this._useReflectionFresnelFromSpecular = false;
  28549. _this._useGlossinessFromSpecularMapAlpha = false;
  28550. _this._maxSimultaneousLights = 4;
  28551. /**
  28552. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  28553. */
  28554. _this._invertNormalMapX = false;
  28555. /**
  28556. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  28557. */
  28558. _this._invertNormalMapY = false;
  28559. /**
  28560. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  28561. */
  28562. _this._twoSidedLighting = false;
  28563. _this._renderTargets = new BABYLON.SmartArray(16);
  28564. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  28565. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  28566. // Setup the default processing configuration to the scene.
  28567. _this._attachImageProcessingConfiguration(null);
  28568. _this.getRenderTargetTextures = function () {
  28569. _this._renderTargets.reset();
  28570. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  28571. _this._renderTargets.push(_this._reflectionTexture);
  28572. }
  28573. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  28574. _this._renderTargets.push(_this._refractionTexture);
  28575. }
  28576. return _this._renderTargets;
  28577. };
  28578. return _this;
  28579. }
  28580. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  28581. /**
  28582. * Gets the image processing configuration used either in this material.
  28583. */
  28584. get: function () {
  28585. return this._imageProcessingConfiguration;
  28586. },
  28587. /**
  28588. * Sets the Default image processing configuration used either in the this material.
  28589. *
  28590. * If sets to null, the scene one is in use.
  28591. */
  28592. set: function (value) {
  28593. this._attachImageProcessingConfiguration(value);
  28594. // Ensure the effect will be rebuilt.
  28595. this._markAllSubMeshesAsTexturesDirty();
  28596. },
  28597. enumerable: true,
  28598. configurable: true
  28599. });
  28600. /**
  28601. * Attaches a new image processing configuration to the Standard Material.
  28602. * @param configuration
  28603. */
  28604. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  28605. var _this = this;
  28606. if (configuration === this._imageProcessingConfiguration) {
  28607. return;
  28608. }
  28609. // Detaches observer.
  28610. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  28611. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  28612. }
  28613. // Pick the scene configuration if needed.
  28614. if (!configuration) {
  28615. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  28616. }
  28617. else {
  28618. this._imageProcessingConfiguration = configuration;
  28619. }
  28620. // Attaches observer.
  28621. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  28622. _this._markAllSubMeshesAsImageProcessingDirty();
  28623. });
  28624. };
  28625. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  28626. /**
  28627. * Gets wether the color curves effect is enabled.
  28628. */
  28629. get: function () {
  28630. return this.imageProcessingConfiguration.colorCurvesEnabled;
  28631. },
  28632. /**
  28633. * Sets wether the color curves effect is enabled.
  28634. */
  28635. set: function (value) {
  28636. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  28637. },
  28638. enumerable: true,
  28639. configurable: true
  28640. });
  28641. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  28642. /**
  28643. * Gets wether the color grading effect is enabled.
  28644. */
  28645. get: function () {
  28646. return this.imageProcessingConfiguration.colorGradingEnabled;
  28647. },
  28648. /**
  28649. * Gets wether the color grading effect is enabled.
  28650. */
  28651. set: function (value) {
  28652. this.imageProcessingConfiguration.colorGradingEnabled = value;
  28653. },
  28654. enumerable: true,
  28655. configurable: true
  28656. });
  28657. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  28658. /**
  28659. * Gets wether tonemapping is enabled or not.
  28660. */
  28661. get: function () {
  28662. return this._imageProcessingConfiguration.toneMappingEnabled;
  28663. },
  28664. /**
  28665. * Sets wether tonemapping is enabled or not
  28666. */
  28667. set: function (value) {
  28668. this._imageProcessingConfiguration.toneMappingEnabled = value;
  28669. },
  28670. enumerable: true,
  28671. configurable: true
  28672. });
  28673. ;
  28674. ;
  28675. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  28676. /**
  28677. * The camera exposure used on this material.
  28678. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  28679. * This corresponds to a photographic exposure.
  28680. */
  28681. get: function () {
  28682. return this._imageProcessingConfiguration.exposure;
  28683. },
  28684. /**
  28685. * The camera exposure used on this material.
  28686. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  28687. * This corresponds to a photographic exposure.
  28688. */
  28689. set: function (value) {
  28690. this._imageProcessingConfiguration.exposure = value;
  28691. },
  28692. enumerable: true,
  28693. configurable: true
  28694. });
  28695. ;
  28696. ;
  28697. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  28698. /**
  28699. * Gets The camera contrast used on this material.
  28700. */
  28701. get: function () {
  28702. return this._imageProcessingConfiguration.contrast;
  28703. },
  28704. /**
  28705. * Sets The camera contrast used on this material.
  28706. */
  28707. set: function (value) {
  28708. this._imageProcessingConfiguration.contrast = value;
  28709. },
  28710. enumerable: true,
  28711. configurable: true
  28712. });
  28713. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  28714. /**
  28715. * Gets the Color Grading 2D Lookup Texture.
  28716. */
  28717. get: function () {
  28718. return this._imageProcessingConfiguration.colorGradingTexture;
  28719. },
  28720. /**
  28721. * Sets the Color Grading 2D Lookup Texture.
  28722. */
  28723. set: function (value) {
  28724. this._imageProcessingConfiguration.colorGradingTexture = value;
  28725. },
  28726. enumerable: true,
  28727. configurable: true
  28728. });
  28729. StandardMaterial.prototype.getClassName = function () {
  28730. return "StandardMaterial";
  28731. };
  28732. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  28733. get: function () {
  28734. return this._useLogarithmicDepth;
  28735. },
  28736. set: function (value) {
  28737. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  28738. this._markAllSubMeshesAsMiscDirty();
  28739. },
  28740. enumerable: true,
  28741. configurable: true
  28742. });
  28743. StandardMaterial.prototype.needAlphaBlending = function () {
  28744. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  28745. };
  28746. StandardMaterial.prototype.needAlphaTesting = function () {
  28747. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  28748. };
  28749. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  28750. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  28751. };
  28752. StandardMaterial.prototype.getAlphaTestTexture = function () {
  28753. return this._diffuseTexture;
  28754. };
  28755. /**
  28756. * Child classes can use it to update shaders
  28757. */
  28758. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28759. if (this.isFrozen) {
  28760. if (this._wasPreviouslyReady && subMesh.effect) {
  28761. return true;
  28762. }
  28763. }
  28764. if (!subMesh._materialDefines) {
  28765. subMesh._materialDefines = new StandardMaterialDefines();
  28766. }
  28767. var scene = this.getScene();
  28768. var defines = subMesh._materialDefines;
  28769. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  28770. if (defines._renderId === scene.getRenderId()) {
  28771. return true;
  28772. }
  28773. }
  28774. var engine = scene.getEngine();
  28775. // Lights
  28776. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  28777. // Textures
  28778. if (defines._areTexturesDirty) {
  28779. defines._needUVs = false;
  28780. if (scene.texturesEnabled) {
  28781. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  28782. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  28783. return false;
  28784. }
  28785. else {
  28786. defines._needUVs = true;
  28787. defines.DIFFUSE = true;
  28788. }
  28789. }
  28790. else {
  28791. defines.DIFFUSE = false;
  28792. }
  28793. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  28794. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  28795. return false;
  28796. }
  28797. else {
  28798. defines._needUVs = true;
  28799. defines.AMBIENT = true;
  28800. }
  28801. }
  28802. else {
  28803. defines.AMBIENT = false;
  28804. }
  28805. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  28806. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  28807. return false;
  28808. }
  28809. else {
  28810. defines._needUVs = true;
  28811. defines.OPACITY = true;
  28812. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  28813. }
  28814. }
  28815. else {
  28816. defines.OPACITY = false;
  28817. }
  28818. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  28819. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  28820. return false;
  28821. }
  28822. else {
  28823. defines._needNormals = true;
  28824. defines.REFLECTION = true;
  28825. defines.ROUGHNESS = (this._roughness > 0);
  28826. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  28827. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  28828. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  28829. switch (this._reflectionTexture.coordinatesMode) {
  28830. case BABYLON.Texture.CUBIC_MODE:
  28831. case BABYLON.Texture.INVCUBIC_MODE:
  28832. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  28833. break;
  28834. case BABYLON.Texture.EXPLICIT_MODE:
  28835. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  28836. break;
  28837. case BABYLON.Texture.PLANAR_MODE:
  28838. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  28839. break;
  28840. case BABYLON.Texture.PROJECTION_MODE:
  28841. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  28842. break;
  28843. case BABYLON.Texture.SKYBOX_MODE:
  28844. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  28845. break;
  28846. case BABYLON.Texture.SPHERICAL_MODE:
  28847. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  28848. break;
  28849. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  28850. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  28851. break;
  28852. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  28853. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  28854. break;
  28855. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  28856. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  28857. break;
  28858. }
  28859. }
  28860. }
  28861. else {
  28862. defines.REFLECTION = false;
  28863. }
  28864. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  28865. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  28866. return false;
  28867. }
  28868. else {
  28869. defines._needUVs = true;
  28870. defines.EMISSIVE = true;
  28871. }
  28872. }
  28873. else {
  28874. defines.EMISSIVE = false;
  28875. }
  28876. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  28877. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  28878. return false;
  28879. }
  28880. else {
  28881. defines._needUVs = true;
  28882. defines.LIGHTMAP = true;
  28883. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  28884. }
  28885. }
  28886. else {
  28887. defines.LIGHTMAP = false;
  28888. }
  28889. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  28890. if (!this._specularTexture.isReadyOrNotBlocking()) {
  28891. return false;
  28892. }
  28893. else {
  28894. defines._needUVs = true;
  28895. defines.SPECULAR = true;
  28896. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  28897. }
  28898. }
  28899. else {
  28900. defines.SPECULAR = false;
  28901. }
  28902. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  28903. // Bump texure can not be not blocking.
  28904. if (!this._bumpTexture.isReady()) {
  28905. return false;
  28906. }
  28907. else {
  28908. defines._needUVs = true;
  28909. defines.BUMP = true;
  28910. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  28911. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  28912. defines.PARALLAX = this._useParallax;
  28913. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  28914. }
  28915. }
  28916. else {
  28917. defines.BUMP = false;
  28918. }
  28919. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  28920. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  28921. return false;
  28922. }
  28923. else {
  28924. defines._needUVs = true;
  28925. defines.REFRACTION = true;
  28926. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  28927. }
  28928. }
  28929. else {
  28930. defines.REFRACTION = false;
  28931. }
  28932. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  28933. }
  28934. else {
  28935. defines.DIFFUSE = false;
  28936. defines.AMBIENT = false;
  28937. defines.OPACITY = false;
  28938. defines.REFLECTION = false;
  28939. defines.EMISSIVE = false;
  28940. defines.LIGHTMAP = false;
  28941. defines.BUMP = false;
  28942. defines.REFRACTION = false;
  28943. }
  28944. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  28945. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  28946. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  28947. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  28948. }
  28949. if (defines._areImageProcessingDirty) {
  28950. if (!this._imageProcessingConfiguration.isReady()) {
  28951. return false;
  28952. }
  28953. this._imageProcessingConfiguration.prepareDefines(defines);
  28954. }
  28955. if (defines._areFresnelDirty) {
  28956. if (StandardMaterial.FresnelEnabled) {
  28957. // Fresnel
  28958. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  28959. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  28960. this._reflectionFresnelParameters) {
  28961. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  28962. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  28963. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  28964. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  28965. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  28966. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  28967. defines._needNormals = true;
  28968. defines.FRESNEL = true;
  28969. }
  28970. }
  28971. else {
  28972. defines.FRESNEL = false;
  28973. }
  28974. }
  28975. // Misc.
  28976. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  28977. // Attribs
  28978. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  28979. // Values that need to be evaluated on every frame
  28980. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  28981. if (scene._mirroredCameraPosition && defines.BUMP) {
  28982. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  28983. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  28984. defines.markAsUnprocessed();
  28985. }
  28986. // Get correct effect
  28987. if (defines.isDirty) {
  28988. defines.markAsProcessed();
  28989. scene.resetCachedMaterial();
  28990. // Fallbacks
  28991. var fallbacks = new BABYLON.EffectFallbacks();
  28992. if (defines.REFLECTION) {
  28993. fallbacks.addFallback(0, "REFLECTION");
  28994. }
  28995. if (defines.SPECULAR) {
  28996. fallbacks.addFallback(0, "SPECULAR");
  28997. }
  28998. if (defines.BUMP) {
  28999. fallbacks.addFallback(0, "BUMP");
  29000. }
  29001. if (defines.PARALLAX) {
  29002. fallbacks.addFallback(1, "PARALLAX");
  29003. }
  29004. if (defines.PARALLAXOCCLUSION) {
  29005. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  29006. }
  29007. if (defines.SPECULAROVERALPHA) {
  29008. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  29009. }
  29010. if (defines.FOG) {
  29011. fallbacks.addFallback(1, "FOG");
  29012. }
  29013. if (defines.POINTSIZE) {
  29014. fallbacks.addFallback(0, "POINTSIZE");
  29015. }
  29016. if (defines.LOGARITHMICDEPTH) {
  29017. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  29018. }
  29019. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  29020. if (defines.SPECULARTERM) {
  29021. fallbacks.addFallback(0, "SPECULARTERM");
  29022. }
  29023. if (defines.DIFFUSEFRESNEL) {
  29024. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  29025. }
  29026. if (defines.OPACITYFRESNEL) {
  29027. fallbacks.addFallback(2, "OPACITYFRESNEL");
  29028. }
  29029. if (defines.REFLECTIONFRESNEL) {
  29030. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  29031. }
  29032. if (defines.EMISSIVEFRESNEL) {
  29033. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  29034. }
  29035. if (defines.FRESNEL) {
  29036. fallbacks.addFallback(4, "FRESNEL");
  29037. }
  29038. //Attributes
  29039. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29040. if (defines.NORMAL) {
  29041. attribs.push(BABYLON.VertexBuffer.NormalKind);
  29042. }
  29043. if (defines.UV1) {
  29044. attribs.push(BABYLON.VertexBuffer.UVKind);
  29045. }
  29046. if (defines.UV2) {
  29047. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29048. }
  29049. if (defines.VERTEXCOLOR) {
  29050. attribs.push(BABYLON.VertexBuffer.ColorKind);
  29051. }
  29052. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  29053. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  29054. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  29055. var shaderName = "default";
  29056. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  29057. "vFogInfos", "vFogColor", "pointSize",
  29058. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  29059. "mBones",
  29060. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  29061. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  29062. "logarithmicDepthConstant"
  29063. ];
  29064. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  29065. var uniformBuffers = ["Material", "Scene"];
  29066. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  29067. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  29068. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  29069. uniformsNames: uniforms,
  29070. uniformBuffersNames: uniformBuffers,
  29071. samplers: samplers,
  29072. defines: defines,
  29073. maxSimultaneousLights: this._maxSimultaneousLights
  29074. });
  29075. if (this.customShaderNameResolve) {
  29076. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  29077. }
  29078. var join = defines.toString();
  29079. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  29080. attributes: attribs,
  29081. uniformsNames: uniforms,
  29082. uniformBuffersNames: uniformBuffers,
  29083. samplers: samplers,
  29084. defines: join,
  29085. fallbacks: fallbacks,
  29086. onCompiled: this.onCompiled,
  29087. onError: this.onError,
  29088. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  29089. }, engine), defines);
  29090. this.buildUniformLayout();
  29091. }
  29092. if (!subMesh.effect.isReady()) {
  29093. return false;
  29094. }
  29095. defines._renderId = scene.getRenderId();
  29096. this._wasPreviouslyReady = true;
  29097. return true;
  29098. };
  29099. StandardMaterial.prototype.buildUniformLayout = function () {
  29100. // Order is important !
  29101. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  29102. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  29103. this._uniformBuffer.addUniform("opacityParts", 4);
  29104. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  29105. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  29106. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  29107. this._uniformBuffer.addUniform("refractionRightColor", 4);
  29108. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  29109. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  29110. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  29111. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  29112. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  29113. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  29114. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  29115. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  29116. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  29117. this._uniformBuffer.addUniform("vBumpInfos", 3);
  29118. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  29119. this._uniformBuffer.addUniform("ambientMatrix", 16);
  29120. this._uniformBuffer.addUniform("opacityMatrix", 16);
  29121. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  29122. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  29123. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  29124. this._uniformBuffer.addUniform("specularMatrix", 16);
  29125. this._uniformBuffer.addUniform("bumpMatrix", 16);
  29126. this._uniformBuffer.addUniform("refractionMatrix", 16);
  29127. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  29128. this._uniformBuffer.addUniform("vSpecularColor", 4);
  29129. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  29130. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  29131. this._uniformBuffer.addUniform("pointSize", 1);
  29132. this._uniformBuffer.create();
  29133. };
  29134. StandardMaterial.prototype.unbind = function () {
  29135. if (this._activeEffect) {
  29136. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  29137. this._activeEffect.setTexture("reflection2DSampler", null);
  29138. }
  29139. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  29140. this._activeEffect.setTexture("refraction2DSampler", null);
  29141. }
  29142. }
  29143. _super.prototype.unbind.call(this);
  29144. };
  29145. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29146. var scene = this.getScene();
  29147. var defines = subMesh._materialDefines;
  29148. if (!defines) {
  29149. return;
  29150. }
  29151. var effect = subMesh.effect;
  29152. this._activeEffect = effect;
  29153. // Matrices
  29154. this.bindOnlyWorldMatrix(world);
  29155. // Bones
  29156. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  29157. if (this._mustRebind(scene, effect, mesh.visibility)) {
  29158. this._uniformBuffer.bindToEffect(effect, "Material");
  29159. this.bindViewProjection(effect);
  29160. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  29161. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  29162. // Fresnel
  29163. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  29164. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  29165. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  29166. }
  29167. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29168. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  29169. }
  29170. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29171. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  29172. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  29173. }
  29174. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  29175. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  29176. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  29177. }
  29178. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29179. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  29180. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  29181. }
  29182. }
  29183. // Textures
  29184. if (scene.texturesEnabled) {
  29185. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29186. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  29187. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  29188. }
  29189. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29190. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  29191. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  29192. }
  29193. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29194. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  29195. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  29196. }
  29197. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29198. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  29199. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  29200. }
  29201. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29202. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  29203. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  29204. }
  29205. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29206. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  29207. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  29208. }
  29209. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29210. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  29211. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  29212. }
  29213. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  29214. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  29215. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  29216. }
  29217. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29218. var depth = 1.0;
  29219. if (!this._refractionTexture.isCube) {
  29220. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  29221. if (this._refractionTexture.depth) {
  29222. depth = this._refractionTexture.depth;
  29223. }
  29224. }
  29225. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  29226. }
  29227. }
  29228. // Point size
  29229. if (this.pointsCloud) {
  29230. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  29231. }
  29232. if (defines.SPECULARTERM) {
  29233. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  29234. }
  29235. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  29236. // Diffuse
  29237. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  29238. }
  29239. // Textures
  29240. if (scene.texturesEnabled) {
  29241. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29242. effect.setTexture("diffuseSampler", this._diffuseTexture);
  29243. }
  29244. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29245. effect.setTexture("ambientSampler", this._ambientTexture);
  29246. }
  29247. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29248. effect.setTexture("opacitySampler", this._opacityTexture);
  29249. }
  29250. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29251. if (this._reflectionTexture.isCube) {
  29252. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  29253. }
  29254. else {
  29255. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  29256. }
  29257. }
  29258. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29259. effect.setTexture("emissiveSampler", this._emissiveTexture);
  29260. }
  29261. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29262. effect.setTexture("lightmapSampler", this._lightmapTexture);
  29263. }
  29264. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29265. effect.setTexture("specularSampler", this._specularTexture);
  29266. }
  29267. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  29268. effect.setTexture("bumpSampler", this._bumpTexture);
  29269. }
  29270. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29271. var depth = 1.0;
  29272. if (this._refractionTexture.isCube) {
  29273. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  29274. }
  29275. else {
  29276. effect.setTexture("refraction2DSampler", this._refractionTexture);
  29277. }
  29278. }
  29279. }
  29280. // Clip plane
  29281. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  29282. // Colors
  29283. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  29284. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  29285. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  29286. }
  29287. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  29288. // Lights
  29289. if (scene.lightsEnabled && !this._disableLighting) {
  29290. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  29291. }
  29292. // View
  29293. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  29294. this.bindView(effect);
  29295. }
  29296. // Fog
  29297. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  29298. // Morph targets
  29299. if (defines.NUM_MORPH_INFLUENCERS) {
  29300. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  29301. }
  29302. // Log. depth
  29303. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  29304. // image processing
  29305. this._imageProcessingConfiguration.bind(this._activeEffect);
  29306. }
  29307. this._uniformBuffer.update();
  29308. this._afterBind(mesh, this._activeEffect);
  29309. };
  29310. StandardMaterial.prototype.getAnimatables = function () {
  29311. var results = [];
  29312. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  29313. results.push(this._diffuseTexture);
  29314. }
  29315. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  29316. results.push(this._ambientTexture);
  29317. }
  29318. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  29319. results.push(this._opacityTexture);
  29320. }
  29321. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  29322. results.push(this._reflectionTexture);
  29323. }
  29324. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  29325. results.push(this._emissiveTexture);
  29326. }
  29327. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  29328. results.push(this._specularTexture);
  29329. }
  29330. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  29331. results.push(this._bumpTexture);
  29332. }
  29333. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  29334. results.push(this._lightmapTexture);
  29335. }
  29336. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  29337. results.push(this._refractionTexture);
  29338. }
  29339. return results;
  29340. };
  29341. StandardMaterial.prototype.getActiveTextures = function () {
  29342. var activeTextures = _super.prototype.getActiveTextures.call(this);
  29343. if (this._diffuseTexture) {
  29344. activeTextures.push(this._diffuseTexture);
  29345. }
  29346. if (this._ambientTexture) {
  29347. activeTextures.push(this._ambientTexture);
  29348. }
  29349. if (this._opacityTexture) {
  29350. activeTextures.push(this._opacityTexture);
  29351. }
  29352. if (this._reflectionTexture) {
  29353. activeTextures.push(this._reflectionTexture);
  29354. }
  29355. if (this._emissiveTexture) {
  29356. activeTextures.push(this._emissiveTexture);
  29357. }
  29358. if (this._specularTexture) {
  29359. activeTextures.push(this._specularTexture);
  29360. }
  29361. if (this._bumpTexture) {
  29362. activeTextures.push(this._bumpTexture);
  29363. }
  29364. if (this._lightmapTexture) {
  29365. activeTextures.push(this._lightmapTexture);
  29366. }
  29367. if (this._refractionTexture) {
  29368. activeTextures.push(this._refractionTexture);
  29369. }
  29370. return activeTextures;
  29371. };
  29372. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29373. if (forceDisposeTextures) {
  29374. if (this._diffuseTexture) {
  29375. this._diffuseTexture.dispose();
  29376. }
  29377. if (this._ambientTexture) {
  29378. this._ambientTexture.dispose();
  29379. }
  29380. if (this._opacityTexture) {
  29381. this._opacityTexture.dispose();
  29382. }
  29383. if (this._reflectionTexture) {
  29384. this._reflectionTexture.dispose();
  29385. }
  29386. if (this._emissiveTexture) {
  29387. this._emissiveTexture.dispose();
  29388. }
  29389. if (this._specularTexture) {
  29390. this._specularTexture.dispose();
  29391. }
  29392. if (this._bumpTexture) {
  29393. this._bumpTexture.dispose();
  29394. }
  29395. if (this._lightmapTexture) {
  29396. this._lightmapTexture.dispose();
  29397. }
  29398. if (this._refractionTexture) {
  29399. this._refractionTexture.dispose();
  29400. }
  29401. }
  29402. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  29403. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  29404. }
  29405. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  29406. };
  29407. StandardMaterial.prototype.clone = function (name) {
  29408. var _this = this;
  29409. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  29410. result.name = name;
  29411. result.id = name;
  29412. return result;
  29413. };
  29414. StandardMaterial.prototype.serialize = function () {
  29415. return BABYLON.SerializationHelper.Serialize(this);
  29416. };
  29417. // Statics
  29418. StandardMaterial.Parse = function (source, scene, rootUrl) {
  29419. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  29420. };
  29421. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  29422. get: function () {
  29423. return StandardMaterial._DiffuseTextureEnabled;
  29424. },
  29425. set: function (value) {
  29426. if (StandardMaterial._DiffuseTextureEnabled === value) {
  29427. return;
  29428. }
  29429. StandardMaterial._DiffuseTextureEnabled = value;
  29430. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29431. },
  29432. enumerable: true,
  29433. configurable: true
  29434. });
  29435. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  29436. get: function () {
  29437. return StandardMaterial._AmbientTextureEnabled;
  29438. },
  29439. set: function (value) {
  29440. if (StandardMaterial._AmbientTextureEnabled === value) {
  29441. return;
  29442. }
  29443. StandardMaterial._AmbientTextureEnabled = value;
  29444. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29445. },
  29446. enumerable: true,
  29447. configurable: true
  29448. });
  29449. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  29450. get: function () {
  29451. return StandardMaterial._OpacityTextureEnabled;
  29452. },
  29453. set: function (value) {
  29454. if (StandardMaterial._OpacityTextureEnabled === value) {
  29455. return;
  29456. }
  29457. StandardMaterial._OpacityTextureEnabled = value;
  29458. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29459. },
  29460. enumerable: true,
  29461. configurable: true
  29462. });
  29463. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  29464. get: function () {
  29465. return StandardMaterial._ReflectionTextureEnabled;
  29466. },
  29467. set: function (value) {
  29468. if (StandardMaterial._ReflectionTextureEnabled === value) {
  29469. return;
  29470. }
  29471. StandardMaterial._ReflectionTextureEnabled = value;
  29472. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29473. },
  29474. enumerable: true,
  29475. configurable: true
  29476. });
  29477. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  29478. get: function () {
  29479. return StandardMaterial._EmissiveTextureEnabled;
  29480. },
  29481. set: function (value) {
  29482. if (StandardMaterial._EmissiveTextureEnabled === value) {
  29483. return;
  29484. }
  29485. StandardMaterial._EmissiveTextureEnabled = value;
  29486. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29487. },
  29488. enumerable: true,
  29489. configurable: true
  29490. });
  29491. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  29492. get: function () {
  29493. return StandardMaterial._SpecularTextureEnabled;
  29494. },
  29495. set: function (value) {
  29496. if (StandardMaterial._SpecularTextureEnabled === value) {
  29497. return;
  29498. }
  29499. StandardMaterial._SpecularTextureEnabled = value;
  29500. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29501. },
  29502. enumerable: true,
  29503. configurable: true
  29504. });
  29505. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  29506. get: function () {
  29507. return StandardMaterial._BumpTextureEnabled;
  29508. },
  29509. set: function (value) {
  29510. if (StandardMaterial._BumpTextureEnabled === value) {
  29511. return;
  29512. }
  29513. StandardMaterial._BumpTextureEnabled = value;
  29514. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29515. },
  29516. enumerable: true,
  29517. configurable: true
  29518. });
  29519. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  29520. get: function () {
  29521. return StandardMaterial._LightmapTextureEnabled;
  29522. },
  29523. set: function (value) {
  29524. if (StandardMaterial._LightmapTextureEnabled === value) {
  29525. return;
  29526. }
  29527. StandardMaterial._LightmapTextureEnabled = value;
  29528. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29529. },
  29530. enumerable: true,
  29531. configurable: true
  29532. });
  29533. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  29534. get: function () {
  29535. return StandardMaterial._RefractionTextureEnabled;
  29536. },
  29537. set: function (value) {
  29538. if (StandardMaterial._RefractionTextureEnabled === value) {
  29539. return;
  29540. }
  29541. StandardMaterial._RefractionTextureEnabled = value;
  29542. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29543. },
  29544. enumerable: true,
  29545. configurable: true
  29546. });
  29547. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  29548. get: function () {
  29549. return StandardMaterial._ColorGradingTextureEnabled;
  29550. },
  29551. set: function (value) {
  29552. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  29553. return;
  29554. }
  29555. StandardMaterial._ColorGradingTextureEnabled = value;
  29556. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29557. },
  29558. enumerable: true,
  29559. configurable: true
  29560. });
  29561. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  29562. get: function () {
  29563. return StandardMaterial._FresnelEnabled;
  29564. },
  29565. set: function (value) {
  29566. if (StandardMaterial._FresnelEnabled === value) {
  29567. return;
  29568. }
  29569. StandardMaterial._FresnelEnabled = value;
  29570. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  29571. },
  29572. enumerable: true,
  29573. configurable: true
  29574. });
  29575. return StandardMaterial;
  29576. }(BABYLON.PushMaterial));
  29577. // Flags used to enable or disable a type of texture for all Standard Materials
  29578. StandardMaterial._DiffuseTextureEnabled = true;
  29579. StandardMaterial._AmbientTextureEnabled = true;
  29580. StandardMaterial._OpacityTextureEnabled = true;
  29581. StandardMaterial._ReflectionTextureEnabled = true;
  29582. StandardMaterial._EmissiveTextureEnabled = true;
  29583. StandardMaterial._SpecularTextureEnabled = true;
  29584. StandardMaterial._BumpTextureEnabled = true;
  29585. StandardMaterial._LightmapTextureEnabled = true;
  29586. StandardMaterial._RefractionTextureEnabled = true;
  29587. StandardMaterial._ColorGradingTextureEnabled = true;
  29588. StandardMaterial._FresnelEnabled = true;
  29589. __decorate([
  29590. BABYLON.serializeAsTexture("diffuseTexture")
  29591. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  29592. __decorate([
  29593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29594. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  29595. __decorate([
  29596. BABYLON.serializeAsTexture("ambientTexture")
  29597. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  29598. __decorate([
  29599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29600. ], StandardMaterial.prototype, "ambientTexture", void 0);
  29601. __decorate([
  29602. BABYLON.serializeAsTexture("opacityTexture")
  29603. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  29604. __decorate([
  29605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29606. ], StandardMaterial.prototype, "opacityTexture", void 0);
  29607. __decorate([
  29608. BABYLON.serializeAsTexture("reflectionTexture")
  29609. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  29610. __decorate([
  29611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29612. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  29613. __decorate([
  29614. BABYLON.serializeAsTexture("emissiveTexture")
  29615. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  29616. __decorate([
  29617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29618. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  29619. __decorate([
  29620. BABYLON.serializeAsTexture("specularTexture")
  29621. ], StandardMaterial.prototype, "_specularTexture", void 0);
  29622. __decorate([
  29623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29624. ], StandardMaterial.prototype, "specularTexture", void 0);
  29625. __decorate([
  29626. BABYLON.serializeAsTexture("bumpTexture")
  29627. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  29628. __decorate([
  29629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29630. ], StandardMaterial.prototype, "bumpTexture", void 0);
  29631. __decorate([
  29632. BABYLON.serializeAsTexture("lightmapTexture")
  29633. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  29634. __decorate([
  29635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29636. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  29637. __decorate([
  29638. BABYLON.serializeAsTexture("refractionTexture")
  29639. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  29640. __decorate([
  29641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29642. ], StandardMaterial.prototype, "refractionTexture", void 0);
  29643. __decorate([
  29644. BABYLON.serializeAsColor3("ambient")
  29645. ], StandardMaterial.prototype, "ambientColor", void 0);
  29646. __decorate([
  29647. BABYLON.serializeAsColor3("diffuse")
  29648. ], StandardMaterial.prototype, "diffuseColor", void 0);
  29649. __decorate([
  29650. BABYLON.serializeAsColor3("specular")
  29651. ], StandardMaterial.prototype, "specularColor", void 0);
  29652. __decorate([
  29653. BABYLON.serializeAsColor3("emissive")
  29654. ], StandardMaterial.prototype, "emissiveColor", void 0);
  29655. __decorate([
  29656. BABYLON.serialize()
  29657. ], StandardMaterial.prototype, "specularPower", void 0);
  29658. __decorate([
  29659. BABYLON.serialize("useAlphaFromDiffuseTexture")
  29660. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  29661. __decorate([
  29662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29663. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  29664. __decorate([
  29665. BABYLON.serialize("useEmissiveAsIllumination")
  29666. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  29667. __decorate([
  29668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29669. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  29670. __decorate([
  29671. BABYLON.serialize("linkEmissiveWithDiffuse")
  29672. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  29673. __decorate([
  29674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29675. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  29676. __decorate([
  29677. BABYLON.serialize("useSpecularOverAlpha")
  29678. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  29679. __decorate([
  29680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29681. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  29682. __decorate([
  29683. BABYLON.serialize("useReflectionOverAlpha")
  29684. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  29685. __decorate([
  29686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29687. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  29688. __decorate([
  29689. BABYLON.serialize("disableLighting")
  29690. ], StandardMaterial.prototype, "_disableLighting", void 0);
  29691. __decorate([
  29692. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  29693. ], StandardMaterial.prototype, "disableLighting", void 0);
  29694. __decorate([
  29695. BABYLON.serialize("useParallax")
  29696. ], StandardMaterial.prototype, "_useParallax", void 0);
  29697. __decorate([
  29698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29699. ], StandardMaterial.prototype, "useParallax", void 0);
  29700. __decorate([
  29701. BABYLON.serialize("useParallaxOcclusion")
  29702. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  29703. __decorate([
  29704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29705. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  29706. __decorate([
  29707. BABYLON.serialize()
  29708. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  29709. __decorate([
  29710. BABYLON.serialize("roughness")
  29711. ], StandardMaterial.prototype, "_roughness", void 0);
  29712. __decorate([
  29713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29714. ], StandardMaterial.prototype, "roughness", void 0);
  29715. __decorate([
  29716. BABYLON.serialize()
  29717. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  29718. __decorate([
  29719. BABYLON.serialize()
  29720. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  29721. __decorate([
  29722. BABYLON.serialize("useLightmapAsShadowmap")
  29723. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  29724. __decorate([
  29725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29726. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  29727. __decorate([
  29728. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  29729. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  29730. __decorate([
  29731. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29732. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  29733. __decorate([
  29734. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  29735. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  29736. __decorate([
  29737. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29738. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  29739. __decorate([
  29740. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  29741. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  29742. __decorate([
  29743. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29744. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  29745. __decorate([
  29746. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  29747. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  29748. __decorate([
  29749. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29750. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  29751. __decorate([
  29752. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  29753. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  29754. __decorate([
  29755. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29756. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  29757. __decorate([
  29758. BABYLON.serialize("useReflectionFresnelFromSpecular")
  29759. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  29760. __decorate([
  29761. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29762. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  29763. __decorate([
  29764. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  29765. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  29766. __decorate([
  29767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29768. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  29769. __decorate([
  29770. BABYLON.serialize("maxSimultaneousLights")
  29771. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  29772. __decorate([
  29773. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  29774. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  29775. __decorate([
  29776. BABYLON.serialize("invertNormalMapX")
  29777. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  29778. __decorate([
  29779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29780. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  29781. __decorate([
  29782. BABYLON.serialize("invertNormalMapY")
  29783. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  29784. __decorate([
  29785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29786. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  29787. __decorate([
  29788. BABYLON.serialize("twoSidedLighting")
  29789. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  29790. __decorate([
  29791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29792. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  29793. __decorate([
  29794. BABYLON.serialize()
  29795. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  29796. BABYLON.StandardMaterial = StandardMaterial;
  29797. })(BABYLON || (BABYLON = {}));
  29798. //# sourceMappingURL=babylon.standardMaterial.js.map
  29799. var BABYLON;
  29800. (function (BABYLON) {
  29801. var PBRMaterialDefines = (function (_super) {
  29802. __extends(PBRMaterialDefines, _super);
  29803. function PBRMaterialDefines() {
  29804. var _this = _super.call(this) || this;
  29805. _this.PBR = true;
  29806. _this.ALBEDO = false;
  29807. _this.AMBIENT = false;
  29808. _this.AMBIENTINGRAYSCALE = false;
  29809. _this.OPACITY = false;
  29810. _this.OPACITYRGB = false;
  29811. _this.REFLECTION = false;
  29812. _this.EMISSIVE = false;
  29813. _this.REFLECTIVITY = false;
  29814. _this.BUMP = false;
  29815. _this.PARALLAX = false;
  29816. _this.PARALLAXOCCLUSION = false;
  29817. _this.SPECULAROVERALPHA = false;
  29818. _this.CLIPPLANE = false;
  29819. _this.ALPHATEST = false;
  29820. _this.ALPHABLEND = false;
  29821. _this.ALPHAFROMALBEDO = false;
  29822. _this.POINTSIZE = false;
  29823. _this.FOG = false;
  29824. _this.SPECULARTERM = false;
  29825. _this.NORMAL = false;
  29826. _this.TANGENT = false;
  29827. _this.UV1 = false;
  29828. _this.UV2 = false;
  29829. _this.VERTEXCOLOR = false;
  29830. _this.VERTEXALPHA = false;
  29831. _this.NUM_BONE_INFLUENCERS = 0;
  29832. _this.BonesPerMesh = 0;
  29833. _this.INSTANCES = false;
  29834. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  29835. _this.MICROSURFACEAUTOMATIC = false;
  29836. _this.LIGHTMAP = false;
  29837. _this.USELIGHTMAPASSHADOWMAP = false;
  29838. _this.REFLECTIONMAP_3D = false;
  29839. _this.REFLECTIONMAP_SPHERICAL = false;
  29840. _this.REFLECTIONMAP_PLANAR = false;
  29841. _this.REFLECTIONMAP_CUBIC = false;
  29842. _this.REFLECTIONMAP_PROJECTION = false;
  29843. _this.REFLECTIONMAP_SKYBOX = false;
  29844. _this.REFLECTIONMAP_EXPLICIT = false;
  29845. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29846. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29847. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  29848. _this.INVERTCUBICMAP = false;
  29849. _this.LOGARITHMICDEPTH = false;
  29850. _this.USESPHERICALFROMREFLECTIONMAP = false;
  29851. _this.REFRACTION = false;
  29852. _this.REFRACTIONMAP_3D = false;
  29853. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  29854. _this.REFRACTIONMAPINLINEARSPACE = false;
  29855. _this.LODBASEDMICROSFURACE = false;
  29856. _this.USEPHYSICALLIGHTFALLOFF = false;
  29857. _this.RADIANCEOVERALPHA = false;
  29858. _this.USEPMREMREFLECTION = false;
  29859. _this.USEPMREMREFRACTION = false;
  29860. _this.INVERTNORMALMAPX = false;
  29861. _this.INVERTNORMALMAPY = false;
  29862. _this.TWOSIDEDLIGHTING = false;
  29863. _this.SHADOWFLOAT = false;
  29864. _this.NORMALXYSCALE = true;
  29865. _this.USERIGHTHANDEDSYSTEM = false;
  29866. _this.METALLICWORKFLOW = false;
  29867. _this.METALLICMAP = false;
  29868. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  29869. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  29870. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  29871. _this.AOSTOREINMETALMAPRED = false;
  29872. _this.MICROSURFACEMAP = false;
  29873. _this.MORPHTARGETS = false;
  29874. _this.MORPHTARGETS_NORMAL = false;
  29875. _this.MORPHTARGETS_TANGENT = false;
  29876. _this.NUM_MORPH_INFLUENCERS = 0;
  29877. _this.ALPHATESTVALUE = 0.5;
  29878. _this.PREMULTIPLYALPHA = false;
  29879. _this.ALPHAFRESNEL = false;
  29880. _this.IMAGEPROCESSING = false;
  29881. _this.VIGNETTE = false;
  29882. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  29883. _this.VIGNETTEBLENDMODEOPAQUE = false;
  29884. _this.TONEMAPPING = false;
  29885. _this.CONTRAST = false;
  29886. _this.COLORCURVES = false;
  29887. _this.COLORGRADING = false;
  29888. _this.SAMPLER3DGREENDEPTH = false;
  29889. _this.SAMPLER3DBGRMAP = false;
  29890. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  29891. _this.EXPOSURE = false;
  29892. _this.rebuild();
  29893. return _this;
  29894. }
  29895. PBRMaterialDefines.prototype.reset = function () {
  29896. _super.prototype.reset.call(this);
  29897. this.ALPHATESTVALUE = 0.5;
  29898. this.PBR = true;
  29899. };
  29900. return PBRMaterialDefines;
  29901. }(BABYLON.MaterialDefines));
  29902. /**
  29903. * The Physically based material base class of BJS.
  29904. *
  29905. * This offers the main features of a standard PBR material.
  29906. * For more information, please refer to the documentation :
  29907. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  29908. */
  29909. var PBRBaseMaterial = (function (_super) {
  29910. __extends(PBRBaseMaterial, _super);
  29911. /**
  29912. * Instantiates a new PBRMaterial instance.
  29913. *
  29914. * @param name The material name
  29915. * @param scene The scene the material will be use in.
  29916. */
  29917. function PBRBaseMaterial(name, scene) {
  29918. var _this = _super.call(this, name, scene) || this;
  29919. /**
  29920. * Intensity of the direct lights e.g. the four lights available in your scene.
  29921. * This impacts both the direct diffuse and specular highlights.
  29922. */
  29923. _this._directIntensity = 1.0;
  29924. /**
  29925. * Intensity of the emissive part of the material.
  29926. * This helps controlling the emissive effect without modifying the emissive color.
  29927. */
  29928. _this._emissiveIntensity = 1.0;
  29929. /**
  29930. * Intensity of the environment e.g. how much the environment will light the object
  29931. * either through harmonics for rough material or through the refelction for shiny ones.
  29932. */
  29933. _this._environmentIntensity = 1.0;
  29934. /**
  29935. * This is a special control allowing the reduction of the specular highlights coming from the
  29936. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  29937. */
  29938. _this._specularIntensity = 1.0;
  29939. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  29940. /**
  29941. * Debug Control allowing disabling the bump map on this material.
  29942. */
  29943. _this._disableBumpMap = false;
  29944. /**
  29945. * AKA Occlusion Texture Intensity in other nomenclature.
  29946. */
  29947. _this._ambientTextureStrength = 1.0;
  29948. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  29949. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  29950. /**
  29951. * AKA Diffuse Color in other nomenclature.
  29952. */
  29953. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  29954. /**
  29955. * AKA Specular Color in other nomenclature.
  29956. */
  29957. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  29958. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  29959. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  29960. /**
  29961. * AKA Glossiness in other nomenclature.
  29962. */
  29963. _this._microSurface = 0.9;
  29964. /**
  29965. * source material index of refraction (IOR)' / 'destination material IOR.
  29966. */
  29967. _this._indexOfRefraction = 0.66;
  29968. /**
  29969. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  29970. */
  29971. _this._invertRefractionY = false;
  29972. /**
  29973. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  29974. * Materials half opaque for instance using refraction could benefit from this control.
  29975. */
  29976. _this._linkRefractionWithTransparency = false;
  29977. _this._useLightmapAsShadowmap = false;
  29978. /**
  29979. * Specifies that the alpha is coming form the albedo channel alpha channel.
  29980. */
  29981. _this._useAlphaFromAlbedoTexture = false;
  29982. /**
  29983. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  29984. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  29985. */
  29986. _this._useSpecularOverAlpha = true;
  29987. /**
  29988. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  29989. */
  29990. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  29991. /**
  29992. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  29993. */
  29994. _this._useRoughnessFromMetallicTextureAlpha = true;
  29995. /**
  29996. * Specifies if the metallic texture contains the roughness information in its green channel.
  29997. */
  29998. _this._useRoughnessFromMetallicTextureGreen = false;
  29999. /**
  30000. * Specifies if the metallic texture contains the metallness information in its blue channel.
  30001. */
  30002. _this._useMetallnessFromMetallicTextureBlue = false;
  30003. /**
  30004. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  30005. */
  30006. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  30007. /**
  30008. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  30009. */
  30010. _this._useAmbientInGrayScale = false;
  30011. /**
  30012. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  30013. * The material will try to infer what glossiness each pixel should be.
  30014. */
  30015. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  30016. /**
  30017. * BJS is using an harcoded light falloff based on a manually sets up range.
  30018. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  30019. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  30020. */
  30021. _this._usePhysicalLightFalloff = true;
  30022. /**
  30023. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  30024. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  30025. */
  30026. _this._useRadianceOverAlpha = true;
  30027. /**
  30028. * Allows using the bump map in parallax mode.
  30029. */
  30030. _this._useParallax = false;
  30031. /**
  30032. * Allows using the bump map in parallax occlusion mode.
  30033. */
  30034. _this._useParallaxOcclusion = false;
  30035. /**
  30036. * Controls the scale bias of the parallax mode.
  30037. */
  30038. _this._parallaxScaleBias = 0.05;
  30039. /**
  30040. * If sets to true, disables all the lights affecting the material.
  30041. */
  30042. _this._disableLighting = false;
  30043. /**
  30044. * Number of Simultaneous lights allowed on the material.
  30045. */
  30046. _this._maxSimultaneousLights = 4;
  30047. /**
  30048. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30049. */
  30050. _this._invertNormalMapX = false;
  30051. /**
  30052. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30053. */
  30054. _this._invertNormalMapY = false;
  30055. /**
  30056. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30057. */
  30058. _this._twoSidedLighting = false;
  30059. /**
  30060. * Defines the alpha limits in alpha test mode.
  30061. */
  30062. _this._alphaCutOff = 0.4;
  30063. /**
  30064. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  30065. */
  30066. _this._forceAlphaTest = false;
  30067. /**
  30068. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  30069. * in your scene composition.
  30070. */
  30071. _this._premultiplyAlpha = false;
  30072. /**
  30073. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  30074. * And/Or occlude the blended part.
  30075. */
  30076. _this._useAlphaFresnel = false;
  30077. _this._renderTargets = new BABYLON.SmartArray(16);
  30078. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30079. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30080. _this._tempColor = new BABYLON.Color3();
  30081. // Setup the default processing configuration to the scene.
  30082. _this._attachImageProcessingConfiguration(null);
  30083. _this.getRenderTargetTextures = function () {
  30084. _this._renderTargets.reset();
  30085. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30086. _this._renderTargets.push(_this._reflectionTexture);
  30087. }
  30088. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30089. _this._renderTargets.push(_this._refractionTexture);
  30090. }
  30091. return _this._renderTargets;
  30092. };
  30093. return _this;
  30094. }
  30095. /**
  30096. * Attaches a new image processing configuration to the PBR Material.
  30097. * @param configuration
  30098. */
  30099. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  30100. var _this = this;
  30101. if (configuration === this._imageProcessingConfiguration) {
  30102. return;
  30103. }
  30104. // Detaches observer.
  30105. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30106. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30107. }
  30108. // Pick the scene configuration if needed.
  30109. if (!configuration) {
  30110. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  30111. }
  30112. else {
  30113. this._imageProcessingConfiguration = configuration;
  30114. }
  30115. // Attaches observer.
  30116. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  30117. _this._markAllSubMeshesAsImageProcessingDirty();
  30118. });
  30119. };
  30120. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  30121. get: function () {
  30122. return this._useLogarithmicDepth;
  30123. },
  30124. set: function (value) {
  30125. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30126. },
  30127. enumerable: true,
  30128. configurable: true
  30129. });
  30130. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  30131. if (this._linkRefractionWithTransparency) {
  30132. return false;
  30133. }
  30134. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  30135. };
  30136. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  30137. if (this._forceAlphaTest) {
  30138. return true;
  30139. }
  30140. if (this._linkRefractionWithTransparency) {
  30141. return false;
  30142. }
  30143. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  30144. };
  30145. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  30146. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  30147. };
  30148. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  30149. return this._albedoTexture;
  30150. };
  30151. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30152. if (this.isFrozen) {
  30153. if (this._wasPreviouslyReady) {
  30154. return true;
  30155. }
  30156. }
  30157. if (!subMesh._materialDefines) {
  30158. subMesh._materialDefines = new PBRMaterialDefines();
  30159. }
  30160. var scene = this.getScene();
  30161. var defines = subMesh._materialDefines;
  30162. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  30163. if (defines._renderId === scene.getRenderId()) {
  30164. return true;
  30165. }
  30166. }
  30167. var engine = scene.getEngine();
  30168. // Lights
  30169. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  30170. defines._needNormals = true;
  30171. // Textures
  30172. if (defines._areTexturesDirty) {
  30173. defines._needUVs = false;
  30174. if (scene.texturesEnabled) {
  30175. if (scene.getEngine().getCaps().textureLOD) {
  30176. defines.LODBASEDMICROSFURACE = true;
  30177. }
  30178. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30179. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  30180. return false;
  30181. }
  30182. defines._needUVs = true;
  30183. defines.ALBEDO = true;
  30184. }
  30185. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30186. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  30187. return false;
  30188. }
  30189. defines._needUVs = true;
  30190. defines.AMBIENT = true;
  30191. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  30192. }
  30193. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30194. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  30195. return false;
  30196. }
  30197. defines._needUVs = true;
  30198. defines.OPACITY = true;
  30199. if (this._opacityTexture.getAlphaFromRGB) {
  30200. defines.OPACITYRGB = true;
  30201. }
  30202. }
  30203. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  30204. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30205. if (!reflectionTexture.isReadyOrNotBlocking()) {
  30206. return false;
  30207. }
  30208. defines.REFLECTION = true;
  30209. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  30210. defines.INVERTCUBICMAP = true;
  30211. }
  30212. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  30213. switch (reflectionTexture.coordinatesMode) {
  30214. case BABYLON.Texture.CUBIC_MODE:
  30215. case BABYLON.Texture.INVCUBIC_MODE:
  30216. defines.REFLECTIONMAP_CUBIC = true;
  30217. break;
  30218. case BABYLON.Texture.EXPLICIT_MODE:
  30219. defines.REFLECTIONMAP_EXPLICIT = true;
  30220. break;
  30221. case BABYLON.Texture.PLANAR_MODE:
  30222. defines.REFLECTIONMAP_PLANAR = true;
  30223. break;
  30224. case BABYLON.Texture.PROJECTION_MODE:
  30225. defines.REFLECTIONMAP_PROJECTION = true;
  30226. break;
  30227. case BABYLON.Texture.SKYBOX_MODE:
  30228. defines.REFLECTIONMAP_SKYBOX = true;
  30229. break;
  30230. case BABYLON.Texture.SPHERICAL_MODE:
  30231. defines.REFLECTIONMAP_SPHERICAL = true;
  30232. break;
  30233. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30234. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  30235. break;
  30236. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30237. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  30238. break;
  30239. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  30240. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  30241. break;
  30242. }
  30243. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  30244. defines.USESPHERICALFROMREFLECTIONMAP = true;
  30245. if (reflectionTexture.isPMREM) {
  30246. defines.USEPMREMREFLECTION = true;
  30247. }
  30248. }
  30249. }
  30250. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30251. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  30252. return false;
  30253. }
  30254. defines._needUVs = true;
  30255. defines.LIGHTMAP = true;
  30256. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  30257. }
  30258. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30259. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  30260. return false;
  30261. }
  30262. defines._needUVs = true;
  30263. defines.EMISSIVE = true;
  30264. }
  30265. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30266. if (this._metallicTexture) {
  30267. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  30268. return false;
  30269. }
  30270. defines._needUVs = true;
  30271. defines.METALLICWORKFLOW = true;
  30272. defines.METALLICMAP = true;
  30273. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  30274. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  30275. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  30276. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  30277. }
  30278. else if (this._reflectivityTexture) {
  30279. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  30280. return false;
  30281. }
  30282. defines._needUVs = true;
  30283. defines.REFLECTIVITY = true;
  30284. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  30285. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  30286. }
  30287. if (this._microSurfaceTexture) {
  30288. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  30289. return false;
  30290. }
  30291. defines._needUVs = true;
  30292. defines.MICROSURFACEMAP = true;
  30293. }
  30294. }
  30295. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30296. // Bump texure can not be none blocking.
  30297. if (!this._bumpTexture.isReady()) {
  30298. return false;
  30299. }
  30300. defines._needUVs = true;
  30301. defines.BUMP = true;
  30302. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30303. defines.PARALLAX = true;
  30304. if (this._useParallaxOcclusion) {
  30305. defines.PARALLAXOCCLUSION = true;
  30306. }
  30307. }
  30308. if (this._invertNormalMapX) {
  30309. defines.INVERTNORMALMAPX = true;
  30310. }
  30311. if (this._invertNormalMapY) {
  30312. defines.INVERTNORMALMAPY = true;
  30313. }
  30314. if (scene._mirroredCameraPosition) {
  30315. defines.INVERTNORMALMAPX = !defines.INVERTNORMALMAPX;
  30316. defines.INVERTNORMALMAPY = !defines.INVERTNORMALMAPY;
  30317. }
  30318. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  30319. }
  30320. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30321. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  30322. return false;
  30323. }
  30324. defines._needUVs = true;
  30325. defines.REFRACTION = true;
  30326. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  30327. if (this._linkRefractionWithTransparency) {
  30328. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  30329. }
  30330. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  30331. defines.REFRACTIONMAPINLINEARSPACE = true;
  30332. if (this._refractionTexture.isPMREM) {
  30333. defines.USEPMREMREFRACTION = true;
  30334. }
  30335. }
  30336. }
  30337. if (this._shouldUseAlphaFromAlbedoTexture()) {
  30338. defines.ALPHAFROMALBEDO = true;
  30339. }
  30340. }
  30341. if (this._useSpecularOverAlpha) {
  30342. defines.SPECULAROVERALPHA = true;
  30343. }
  30344. if (this._usePhysicalLightFalloff) {
  30345. defines.USEPHYSICALLIGHTFALLOFF = true;
  30346. }
  30347. if (this._useRadianceOverAlpha) {
  30348. defines.RADIANCEOVERALPHA = true;
  30349. }
  30350. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  30351. defines.METALLICWORKFLOW = true;
  30352. }
  30353. if (!this.backFaceCulling && this._twoSidedLighting) {
  30354. defines.TWOSIDEDLIGHTING = true;
  30355. }
  30356. defines.ALPHATESTVALUE = this._alphaCutOff;
  30357. defines.PREMULTIPLYALPHA = this._premultiplyAlpha;
  30358. defines.ALPHABLEND = this.needAlphaBlending();
  30359. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  30360. }
  30361. if (defines._areImageProcessingDirty) {
  30362. if (!this._imageProcessingConfiguration.isReady()) {
  30363. return false;
  30364. }
  30365. this._imageProcessingConfiguration.prepareDefines(defines);
  30366. }
  30367. // Misc.
  30368. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  30369. // Values that need to be evaluated on every frame
  30370. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  30371. // Attribs
  30372. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  30373. if (mesh) {
  30374. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30375. mesh.createNormals(true);
  30376. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  30377. }
  30378. }
  30379. }
  30380. // Get correct effect
  30381. if (defines.isDirty) {
  30382. defines.markAsProcessed();
  30383. scene.resetCachedMaterial();
  30384. // Fallbacks
  30385. var fallbacks = new BABYLON.EffectFallbacks();
  30386. if (defines.REFLECTION) {
  30387. fallbacks.addFallback(0, "REFLECTION");
  30388. }
  30389. if (defines.REFRACTION) {
  30390. fallbacks.addFallback(0, "REFRACTION");
  30391. }
  30392. if (defines.REFLECTIVITY) {
  30393. fallbacks.addFallback(0, "REFLECTIVITY");
  30394. }
  30395. if (defines.BUMP) {
  30396. fallbacks.addFallback(0, "BUMP");
  30397. }
  30398. if (defines.PARALLAX) {
  30399. fallbacks.addFallback(1, "PARALLAX");
  30400. }
  30401. if (defines.PARALLAXOCCLUSION) {
  30402. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30403. }
  30404. if (defines.SPECULAROVERALPHA) {
  30405. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30406. }
  30407. if (defines.FOG) {
  30408. fallbacks.addFallback(1, "FOG");
  30409. }
  30410. if (defines.POINTSIZE) {
  30411. fallbacks.addFallback(0, "POINTSIZE");
  30412. }
  30413. if (defines.LOGARITHMICDEPTH) {
  30414. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30415. }
  30416. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  30417. if (defines.SPECULARTERM) {
  30418. fallbacks.addFallback(0, "SPECULARTERM");
  30419. }
  30420. if (defines.NUM_BONE_INFLUENCERS > 0) {
  30421. fallbacks.addCPUSkinningFallback(0, mesh);
  30422. }
  30423. //Attributes
  30424. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30425. if (defines.NORMAL) {
  30426. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30427. }
  30428. if (defines.TANGENT) {
  30429. attribs.push(BABYLON.VertexBuffer.TangentKind);
  30430. }
  30431. if (defines.UV1) {
  30432. attribs.push(BABYLON.VertexBuffer.UVKind);
  30433. }
  30434. if (defines.UV2) {
  30435. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30436. }
  30437. if (defines.VERTEXCOLOR) {
  30438. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30439. }
  30440. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  30441. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  30442. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  30443. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  30444. "vFogInfos", "vFogColor", "pointSize",
  30445. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30446. "mBones",
  30447. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30448. "vLightingIntensity",
  30449. "logarithmicDepthConstant",
  30450. "vSphericalX", "vSphericalY", "vSphericalZ",
  30451. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  30452. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  30453. "vMicrosurfaceTextureLods"
  30454. ];
  30455. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30456. var uniformBuffers = ["Material", "Scene"];
  30457. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  30458. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  30459. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  30460. uniformsNames: uniforms,
  30461. uniformBuffersNames: uniformBuffers,
  30462. samplers: samplers,
  30463. defines: defines,
  30464. maxSimultaneousLights: this._maxSimultaneousLights
  30465. });
  30466. var onCompiled = function (effect) {
  30467. if (this.onCompiled) {
  30468. this.onCompiled(effect);
  30469. }
  30470. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  30471. }.bind(this);
  30472. var join = defines.toString();
  30473. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  30474. attributes: attribs,
  30475. uniformsNames: uniforms,
  30476. uniformBuffersNames: uniformBuffers,
  30477. samplers: samplers,
  30478. defines: join,
  30479. fallbacks: fallbacks,
  30480. onCompiled: onCompiled,
  30481. onError: this.onError,
  30482. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  30483. }, engine), defines);
  30484. this.buildUniformLayout();
  30485. }
  30486. if (!subMesh.effect.isReady()) {
  30487. return false;
  30488. }
  30489. defines._renderId = scene.getRenderId();
  30490. this._wasPreviouslyReady = true;
  30491. return true;
  30492. };
  30493. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  30494. // Order is important !
  30495. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  30496. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  30497. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  30498. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  30499. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  30500. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  30501. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  30502. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  30503. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  30504. this._uniformBuffer.addUniform("vBumpInfos", 3);
  30505. this._uniformBuffer.addUniform("albedoMatrix", 16);
  30506. this._uniformBuffer.addUniform("ambientMatrix", 16);
  30507. this._uniformBuffer.addUniform("opacityMatrix", 16);
  30508. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  30509. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  30510. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  30511. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  30512. this._uniformBuffer.addUniform("bumpMatrix", 16);
  30513. this._uniformBuffer.addUniform("refractionMatrix", 16);
  30514. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  30515. this._uniformBuffer.addUniform("vReflectionColor", 3);
  30516. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  30517. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  30518. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  30519. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  30520. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  30521. this._uniformBuffer.addUniform("pointSize", 1);
  30522. this._uniformBuffer.create();
  30523. };
  30524. PBRBaseMaterial.prototype.unbind = function () {
  30525. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  30526. this._uniformBuffer.setTexture("reflection2DSampler", null);
  30527. }
  30528. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  30529. this._uniformBuffer.setTexture("refraction2DSampler", null);
  30530. }
  30531. _super.prototype.unbind.call(this);
  30532. };
  30533. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30534. this._activeEffect.setMatrix("world", world);
  30535. };
  30536. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30537. var scene = this.getScene();
  30538. var defines = subMesh._materialDefines;
  30539. if (!defines) {
  30540. return;
  30541. }
  30542. var effect = subMesh.effect;
  30543. this._activeEffect = effect;
  30544. // Matrices
  30545. this.bindOnlyWorldMatrix(world);
  30546. // Bones
  30547. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  30548. if (this._mustRebind(scene, effect, mesh.visibility)) {
  30549. this._uniformBuffer.bindToEffect(effect, "Material");
  30550. this.bindViewProjection(effect);
  30551. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  30552. // Texture uniforms
  30553. if (scene.texturesEnabled) {
  30554. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30555. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  30556. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  30557. }
  30558. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30559. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  30560. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  30561. }
  30562. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30563. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  30564. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  30565. }
  30566. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  30567. ;
  30568. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30569. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  30570. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  30571. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  30572. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  30573. this._activeEffect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  30574. this._activeEffect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  30575. this._activeEffect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  30576. this._activeEffect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  30577. this._activeEffect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  30578. this._activeEffect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  30579. this._activeEffect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  30580. this._activeEffect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  30581. this._activeEffect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  30582. }
  30583. }
  30584. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30585. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  30586. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  30587. }
  30588. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30589. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  30590. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  30591. }
  30592. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30593. if (this._metallicTexture) {
  30594. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  30595. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  30596. }
  30597. else if (this._reflectivityTexture) {
  30598. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  30599. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  30600. }
  30601. if (this._microSurfaceTexture) {
  30602. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  30603. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  30604. }
  30605. }
  30606. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30607. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  30608. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  30609. }
  30610. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30611. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  30612. var depth = 1.0;
  30613. if (!this._refractionTexture.isCube) {
  30614. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  30615. if (this._refractionTexture.depth) {
  30616. depth = this._refractionTexture.depth;
  30617. }
  30618. }
  30619. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  30620. }
  30621. if ((reflectionTexture || this._refractionTexture)) {
  30622. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  30623. }
  30624. }
  30625. // Point size
  30626. if (this.pointsCloud) {
  30627. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  30628. }
  30629. // Colors
  30630. if (defines.METALLICWORKFLOW) {
  30631. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  30632. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  30633. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  30634. }
  30635. else {
  30636. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  30637. }
  30638. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  30639. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  30640. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  30641. // Misc
  30642. this._lightingInfos.x = this._directIntensity;
  30643. this._lightingInfos.y = this._emissiveIntensity;
  30644. this._lightingInfos.z = this._environmentIntensity;
  30645. this._lightingInfos.w = this._specularIntensity;
  30646. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  30647. }
  30648. // Textures
  30649. if (scene.texturesEnabled) {
  30650. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30651. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  30652. }
  30653. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30654. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  30655. }
  30656. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30657. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  30658. }
  30659. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30660. if (reflectionTexture.isCube) {
  30661. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  30662. }
  30663. else {
  30664. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  30665. }
  30666. }
  30667. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30668. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  30669. }
  30670. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30671. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  30672. }
  30673. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30674. if (this._metallicTexture) {
  30675. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  30676. }
  30677. else if (this._reflectivityTexture) {
  30678. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  30679. }
  30680. if (this._microSurfaceTexture) {
  30681. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  30682. }
  30683. }
  30684. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30685. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  30686. }
  30687. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30688. if (this._refractionTexture.isCube) {
  30689. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  30690. }
  30691. else {
  30692. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  30693. }
  30694. }
  30695. }
  30696. // Clip plane
  30697. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  30698. // Colors
  30699. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  30700. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  30701. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30702. }
  30703. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  30704. // Lights
  30705. if (scene.lightsEnabled && !this._disableLighting) {
  30706. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  30707. }
  30708. // View
  30709. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  30710. this.bindView(effect);
  30711. }
  30712. // Fog
  30713. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  30714. // Morph targets
  30715. if (defines.NUM_MORPH_INFLUENCERS) {
  30716. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  30717. }
  30718. // image processing
  30719. this._imageProcessingConfiguration.bind(this._activeEffect);
  30720. // Log. depth
  30721. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  30722. }
  30723. this._uniformBuffer.update();
  30724. this._afterBind(mesh);
  30725. scene = null;
  30726. };
  30727. PBRBaseMaterial.prototype.getAnimatables = function () {
  30728. var results = [];
  30729. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  30730. results.push(this._albedoTexture);
  30731. }
  30732. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  30733. results.push(this._ambientTexture);
  30734. }
  30735. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  30736. results.push(this._opacityTexture);
  30737. }
  30738. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  30739. results.push(this._reflectionTexture);
  30740. }
  30741. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  30742. results.push(this._emissiveTexture);
  30743. }
  30744. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  30745. results.push(this._metallicTexture);
  30746. }
  30747. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  30748. results.push(this._reflectivityTexture);
  30749. }
  30750. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  30751. results.push(this._bumpTexture);
  30752. }
  30753. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  30754. results.push(this._lightmapTexture);
  30755. }
  30756. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  30757. results.push(this._refractionTexture);
  30758. }
  30759. return results;
  30760. };
  30761. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30762. if (forceDisposeTextures) {
  30763. if (this._albedoTexture) {
  30764. this._albedoTexture.dispose();
  30765. }
  30766. if (this._ambientTexture) {
  30767. this._ambientTexture.dispose();
  30768. }
  30769. if (this._opacityTexture) {
  30770. this._opacityTexture.dispose();
  30771. }
  30772. if (this._reflectionTexture) {
  30773. this._reflectionTexture.dispose();
  30774. }
  30775. if (this._emissiveTexture) {
  30776. this._emissiveTexture.dispose();
  30777. }
  30778. if (this._metallicTexture) {
  30779. this._metallicTexture.dispose();
  30780. }
  30781. if (this._reflectivityTexture) {
  30782. this._reflectivityTexture.dispose();
  30783. }
  30784. if (this._bumpTexture) {
  30785. this._bumpTexture.dispose();
  30786. }
  30787. if (this._lightmapTexture) {
  30788. this._lightmapTexture.dispose();
  30789. }
  30790. if (this._refractionTexture) {
  30791. this._refractionTexture.dispose();
  30792. }
  30793. }
  30794. this._renderTargets.dispose();
  30795. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30796. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30797. }
  30798. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30799. };
  30800. return PBRBaseMaterial;
  30801. }(BABYLON.PushMaterial));
  30802. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  30803. __decorate([
  30804. BABYLON.serializeAsImageProcessingConfiguration()
  30805. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  30806. __decorate([
  30807. BABYLON.serialize()
  30808. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  30809. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  30810. })(BABYLON || (BABYLON = {}));
  30811. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  30812. var BABYLON;
  30813. (function (BABYLON) {
  30814. var Internals;
  30815. (function (Internals) {
  30816. /**
  30817. * The Physically based simple base material of BJS.
  30818. *
  30819. * This enables better naming and convention enforcements on top of the pbrMaterial.
  30820. * It is used as the base class for both the specGloss and metalRough conventions.
  30821. */
  30822. var PBRBaseSimpleMaterial = (function (_super) {
  30823. __extends(PBRBaseSimpleMaterial, _super);
  30824. /**
  30825. * Instantiates a new PBRMaterial instance.
  30826. *
  30827. * @param name The material name
  30828. * @param scene The scene the material will be use in.
  30829. */
  30830. function PBRBaseSimpleMaterial(name, scene) {
  30831. var _this = _super.call(this, name, scene) || this;
  30832. /**
  30833. * Number of Simultaneous lights allowed on the material.
  30834. */
  30835. _this.maxSimultaneousLights = 4;
  30836. /**
  30837. * If sets to true, disables all the lights affecting the material.
  30838. */
  30839. _this.disableLighting = false;
  30840. /**
  30841. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30842. */
  30843. _this.invertNormalMapX = false;
  30844. /**
  30845. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30846. */
  30847. _this.invertNormalMapY = false;
  30848. /**
  30849. * Emissivie color used to self-illuminate the model.
  30850. */
  30851. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30852. /**
  30853. * Occlusion Channel Strenght.
  30854. */
  30855. _this.occlusionStrength = 1.0;
  30856. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  30857. _this._useAmbientInGrayScale = true;
  30858. return _this;
  30859. }
  30860. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  30861. /**
  30862. * Gets the current transparency mode.
  30863. */
  30864. get: function () {
  30865. return this._transparencyMode;
  30866. },
  30867. /**
  30868. * Sets the transparency mode of the material.
  30869. */
  30870. set: function (value) {
  30871. if (this._transparencyMode === value) {
  30872. return;
  30873. }
  30874. this._transparencyMode = value;
  30875. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  30876. this._forceAlphaTest = true;
  30877. }
  30878. else {
  30879. this._forceAlphaTest = false;
  30880. }
  30881. this._markAllSubMeshesAsTexturesDirty();
  30882. },
  30883. enumerable: true,
  30884. configurable: true
  30885. });
  30886. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  30887. /**
  30888. * Gets the current double sided mode.
  30889. */
  30890. get: function () {
  30891. return this._twoSidedLighting;
  30892. },
  30893. /**
  30894. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30895. */
  30896. set: function (value) {
  30897. if (this._twoSidedLighting === value) {
  30898. return;
  30899. }
  30900. this._twoSidedLighting = value;
  30901. this.backFaceCulling = !value;
  30902. this._markAllSubMeshesAsTexturesDirty();
  30903. },
  30904. enumerable: true,
  30905. configurable: true
  30906. });
  30907. /**
  30908. * Specifies wether or not the alpha value of the albedo texture should be used.
  30909. */
  30910. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  30911. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  30912. };
  30913. /**
  30914. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  30915. */
  30916. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  30917. if (this._linkRefractionWithTransparency) {
  30918. return false;
  30919. }
  30920. return (this.alpha < 1.0) ||
  30921. (this._shouldUseAlphaFromAlbedoTexture() &&
  30922. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  30923. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  30924. };
  30925. /**
  30926. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  30927. */
  30928. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  30929. if (this._linkRefractionWithTransparency) {
  30930. return false;
  30931. }
  30932. return this._shouldUseAlphaFromAlbedoTexture() &&
  30933. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  30934. };
  30935. return PBRBaseSimpleMaterial;
  30936. }(BABYLON.PBRBaseMaterial));
  30937. __decorate([
  30938. BABYLON.serialize(),
  30939. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  30940. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  30941. __decorate([
  30942. BABYLON.serialize(),
  30943. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  30944. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  30945. __decorate([
  30946. BABYLON.serializeAsTexture(),
  30947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  30948. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  30949. __decorate([
  30950. BABYLON.serialize(),
  30951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30952. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  30953. __decorate([
  30954. BABYLON.serialize(),
  30955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30956. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  30957. __decorate([
  30958. BABYLON.serializeAsTexture(),
  30959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  30960. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  30961. __decorate([
  30962. BABYLON.serializeAsColor3("emissive"),
  30963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30964. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  30965. __decorate([
  30966. BABYLON.serializeAsTexture(),
  30967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30968. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  30969. __decorate([
  30970. BABYLON.serialize(),
  30971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  30972. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  30973. __decorate([
  30974. BABYLON.serializeAsTexture(),
  30975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  30976. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  30977. __decorate([
  30978. BABYLON.serialize(),
  30979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  30980. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  30981. __decorate([
  30982. BABYLON.serialize()
  30983. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  30984. __decorate([
  30985. BABYLON.serialize()
  30986. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  30987. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  30988. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30989. })(BABYLON || (BABYLON = {}));
  30990. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  30991. var BABYLON;
  30992. (function (BABYLON) {
  30993. /**
  30994. * The Physically based material of BJS.
  30995. *
  30996. * This offers the main features of a standard PBR material.
  30997. * For more information, please refer to the documentation :
  30998. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  30999. */
  31000. var PBRMaterial = (function (_super) {
  31001. __extends(PBRMaterial, _super);
  31002. /**
  31003. * Instantiates a new PBRMaterial instance.
  31004. *
  31005. * @param name The material name
  31006. * @param scene The scene the material will be use in.
  31007. */
  31008. function PBRMaterial(name, scene) {
  31009. var _this = _super.call(this, name, scene) || this;
  31010. /**
  31011. * Intensity of the direct lights e.g. the four lights available in your scene.
  31012. * This impacts both the direct diffuse and specular highlights.
  31013. */
  31014. _this.directIntensity = 1.0;
  31015. /**
  31016. * Intensity of the emissive part of the material.
  31017. * This helps controlling the emissive effect without modifying the emissive color.
  31018. */
  31019. _this.emissiveIntensity = 1.0;
  31020. /**
  31021. * Intensity of the environment e.g. how much the environment will light the object
  31022. * either through harmonics for rough material or through the refelction for shiny ones.
  31023. */
  31024. _this.environmentIntensity = 1.0;
  31025. /**
  31026. * This is a special control allowing the reduction of the specular highlights coming from the
  31027. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  31028. */
  31029. _this.specularIntensity = 1.0;
  31030. /**
  31031. * Debug Control allowing disabling the bump map on this material.
  31032. */
  31033. _this.disableBumpMap = false;
  31034. /**
  31035. * AKA Occlusion Texture Intensity in other nomenclature.
  31036. */
  31037. _this.ambientTextureStrength = 1.0;
  31038. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  31039. /**
  31040. * AKA Diffuse Color in other nomenclature.
  31041. */
  31042. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  31043. /**
  31044. * AKA Specular Color in other nomenclature.
  31045. */
  31046. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  31047. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  31048. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  31049. /**
  31050. * AKA Glossiness in other nomenclature.
  31051. */
  31052. _this.microSurface = 0.9;
  31053. /**
  31054. * source material index of refraction (IOR)' / 'destination material IOR.
  31055. */
  31056. _this.indexOfRefraction = 0.66;
  31057. /**
  31058. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  31059. */
  31060. _this.invertRefractionY = false;
  31061. /**
  31062. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  31063. * Materials half opaque for instance using refraction could benefit from this control.
  31064. */
  31065. _this.linkRefractionWithTransparency = false;
  31066. _this.useLightmapAsShadowmap = false;
  31067. /**
  31068. * Specifies that the alpha is coming form the albedo channel alpha channel.
  31069. */
  31070. _this.useAlphaFromAlbedoTexture = false;
  31071. /**
  31072. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  31073. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  31074. */
  31075. _this.useSpecularOverAlpha = true;
  31076. /**
  31077. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  31078. */
  31079. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  31080. /**
  31081. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  31082. */
  31083. _this.useRoughnessFromMetallicTextureAlpha = true;
  31084. /**
  31085. * Specifies if the metallic texture contains the roughness information in its green channel.
  31086. */
  31087. _this.useRoughnessFromMetallicTextureGreen = false;
  31088. /**
  31089. * Specifies if the metallic texture contains the metallness information in its blue channel.
  31090. */
  31091. _this.useMetallnessFromMetallicTextureBlue = false;
  31092. /**
  31093. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  31094. */
  31095. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  31096. /**
  31097. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  31098. */
  31099. _this.useAmbientInGrayScale = false;
  31100. /**
  31101. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  31102. * The material will try to infer what glossiness each pixel should be.
  31103. */
  31104. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  31105. /**
  31106. * BJS is using an harcoded light falloff based on a manually sets up range.
  31107. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  31108. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  31109. */
  31110. _this.usePhysicalLightFalloff = true;
  31111. /**
  31112. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  31113. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  31114. */
  31115. _this.useRadianceOverAlpha = true;
  31116. /**
  31117. * Allows using the bump map in parallax mode.
  31118. */
  31119. _this.useParallax = false;
  31120. /**
  31121. * Allows using the bump map in parallax occlusion mode.
  31122. */
  31123. _this.useParallaxOcclusion = false;
  31124. /**
  31125. * Controls the scale bias of the parallax mode.
  31126. */
  31127. _this.parallaxScaleBias = 0.05;
  31128. /**
  31129. * If sets to true, disables all the lights affecting the material.
  31130. */
  31131. _this.disableLighting = false;
  31132. /**
  31133. * Number of Simultaneous lights allowed on the material.
  31134. */
  31135. _this.maxSimultaneousLights = 4;
  31136. /**
  31137. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  31138. */
  31139. _this.invertNormalMapX = false;
  31140. /**
  31141. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  31142. */
  31143. _this.invertNormalMapY = false;
  31144. /**
  31145. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  31146. */
  31147. _this.twoSidedLighting = false;
  31148. /**
  31149. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  31150. * in your scene composition.
  31151. */
  31152. _this.premultiplyAlpha = false;
  31153. /**
  31154. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  31155. * And/Or occlude the blended part.
  31156. */
  31157. _this.useAlphaFresnel = false;
  31158. return _this;
  31159. }
  31160. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  31161. /**
  31162. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  31163. */
  31164. get: function () {
  31165. return this._PBRMATERIAL_OPAQUE;
  31166. },
  31167. enumerable: true,
  31168. configurable: true
  31169. });
  31170. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  31171. /**
  31172. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  31173. */
  31174. get: function () {
  31175. return this._PBRMATERIAL_ALPHATEST;
  31176. },
  31177. enumerable: true,
  31178. configurable: true
  31179. });
  31180. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  31181. /**
  31182. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  31183. */
  31184. get: function () {
  31185. return this._PBRMATERIAL_ALPHABLEND;
  31186. },
  31187. enumerable: true,
  31188. configurable: true
  31189. });
  31190. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  31191. /**
  31192. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  31193. * They are also discarded below the alpha cutoff threshold to improve performances.
  31194. */
  31195. get: function () {
  31196. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  31197. },
  31198. enumerable: true,
  31199. configurable: true
  31200. });
  31201. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  31202. /**
  31203. * Gets the image processing configuration used either in this material.
  31204. */
  31205. get: function () {
  31206. return this._imageProcessingConfiguration;
  31207. },
  31208. /**
  31209. * Sets the Default image processing configuration used either in the this material.
  31210. *
  31211. * If sets to null, the scene one is in use.
  31212. */
  31213. set: function (value) {
  31214. this._attachImageProcessingConfiguration(value);
  31215. // Ensure the effect will be rebuilt.
  31216. this._markAllSubMeshesAsTexturesDirty();
  31217. },
  31218. enumerable: true,
  31219. configurable: true
  31220. });
  31221. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  31222. /**
  31223. * Gets wether the color curves effect is enabled.
  31224. */
  31225. get: function () {
  31226. return this.imageProcessingConfiguration.colorCurvesEnabled;
  31227. },
  31228. /**
  31229. * Sets wether the color curves effect is enabled.
  31230. */
  31231. set: function (value) {
  31232. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  31233. },
  31234. enumerable: true,
  31235. configurable: true
  31236. });
  31237. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  31238. /**
  31239. * Gets wether the color grading effect is enabled.
  31240. */
  31241. get: function () {
  31242. return this.imageProcessingConfiguration.colorGradingEnabled;
  31243. },
  31244. /**
  31245. * Gets wether the color grading effect is enabled.
  31246. */
  31247. set: function (value) {
  31248. this.imageProcessingConfiguration.colorGradingEnabled = value;
  31249. },
  31250. enumerable: true,
  31251. configurable: true
  31252. });
  31253. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  31254. /**
  31255. * Gets wether tonemapping is enabled or not.
  31256. */
  31257. get: function () {
  31258. return this._imageProcessingConfiguration.toneMappingEnabled;
  31259. },
  31260. /**
  31261. * Sets wether tonemapping is enabled or not
  31262. */
  31263. set: function (value) {
  31264. this._imageProcessingConfiguration.toneMappingEnabled = value;
  31265. },
  31266. enumerable: true,
  31267. configurable: true
  31268. });
  31269. ;
  31270. ;
  31271. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  31272. /**
  31273. * The camera exposure used on this material.
  31274. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  31275. * This corresponds to a photographic exposure.
  31276. */
  31277. get: function () {
  31278. return this._imageProcessingConfiguration.exposure;
  31279. },
  31280. /**
  31281. * The camera exposure used on this material.
  31282. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  31283. * This corresponds to a photographic exposure.
  31284. */
  31285. set: function (value) {
  31286. this._imageProcessingConfiguration.exposure = value;
  31287. },
  31288. enumerable: true,
  31289. configurable: true
  31290. });
  31291. ;
  31292. ;
  31293. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  31294. /**
  31295. * Gets The camera contrast used on this material.
  31296. */
  31297. get: function () {
  31298. return this._imageProcessingConfiguration.contrast;
  31299. },
  31300. /**
  31301. * Sets The camera contrast used on this material.
  31302. */
  31303. set: function (value) {
  31304. this._imageProcessingConfiguration.contrast = value;
  31305. },
  31306. enumerable: true,
  31307. configurable: true
  31308. });
  31309. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  31310. /**
  31311. * Gets the Color Grading 2D Lookup Texture.
  31312. */
  31313. get: function () {
  31314. return this._imageProcessingConfiguration.colorGradingTexture;
  31315. },
  31316. /**
  31317. * Sets the Color Grading 2D Lookup Texture.
  31318. */
  31319. set: function (value) {
  31320. this._imageProcessingConfiguration.colorGradingTexture = value;
  31321. },
  31322. enumerable: true,
  31323. configurable: true
  31324. });
  31325. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  31326. /**
  31327. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  31328. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  31329. * 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;
  31330. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  31331. */
  31332. get: function () {
  31333. return this._imageProcessingConfiguration.colorCurves;
  31334. },
  31335. /**
  31336. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  31337. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  31338. * 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;
  31339. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  31340. */
  31341. set: function (value) {
  31342. this._imageProcessingConfiguration.colorCurves = value;
  31343. },
  31344. enumerable: true,
  31345. configurable: true
  31346. });
  31347. PBRMaterial.prototype.getClassName = function () {
  31348. return "PBRMaterial";
  31349. };
  31350. PBRMaterial.prototype.getActiveTextures = function () {
  31351. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31352. if (this._albedoTexture) {
  31353. activeTextures.push(this._albedoTexture);
  31354. }
  31355. if (this._ambientTexture) {
  31356. activeTextures.push(this._ambientTexture);
  31357. }
  31358. if (this._opacityTexture) {
  31359. activeTextures.push(this._opacityTexture);
  31360. }
  31361. if (this._reflectionTexture) {
  31362. activeTextures.push(this._reflectionTexture);
  31363. }
  31364. if (this._emissiveTexture) {
  31365. activeTextures.push(this._emissiveTexture);
  31366. }
  31367. if (this._reflectionTexture) {
  31368. activeTextures.push(this._reflectionTexture);
  31369. }
  31370. if (this._metallicTexture) {
  31371. activeTextures.push(this._metallicTexture);
  31372. }
  31373. if (this._microSurfaceTexture) {
  31374. activeTextures.push(this._microSurfaceTexture);
  31375. }
  31376. if (this._bumpTexture) {
  31377. activeTextures.push(this._bumpTexture);
  31378. }
  31379. if (this._lightmapTexture) {
  31380. activeTextures.push(this._lightmapTexture);
  31381. }
  31382. if (this._refractionTexture) {
  31383. activeTextures.push(this._refractionTexture);
  31384. }
  31385. return activeTextures;
  31386. };
  31387. PBRMaterial.prototype.clone = function (name) {
  31388. var _this = this;
  31389. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  31390. };
  31391. PBRMaterial.prototype.serialize = function () {
  31392. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31393. serializationObject.customType = "BABYLON.PBRMaterial";
  31394. return serializationObject;
  31395. };
  31396. // Statics
  31397. PBRMaterial.Parse = function (source, scene, rootUrl) {
  31398. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  31399. };
  31400. return PBRMaterial;
  31401. }(BABYLON.PBRBaseMaterial));
  31402. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  31403. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  31404. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  31405. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  31406. __decorate([
  31407. BABYLON.serialize(),
  31408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31409. ], PBRMaterial.prototype, "directIntensity", void 0);
  31410. __decorate([
  31411. BABYLON.serialize(),
  31412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31413. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  31414. __decorate([
  31415. BABYLON.serialize(),
  31416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31417. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  31418. __decorate([
  31419. BABYLON.serialize(),
  31420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31421. ], PBRMaterial.prototype, "specularIntensity", void 0);
  31422. __decorate([
  31423. BABYLON.serialize(),
  31424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31425. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  31426. __decorate([
  31427. BABYLON.serializeAsTexture(),
  31428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31429. ], PBRMaterial.prototype, "albedoTexture", void 0);
  31430. __decorate([
  31431. BABYLON.serializeAsTexture(),
  31432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31433. ], PBRMaterial.prototype, "ambientTexture", void 0);
  31434. __decorate([
  31435. BABYLON.serialize(),
  31436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31437. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  31438. __decorate([
  31439. BABYLON.serializeAsTexture(),
  31440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31441. ], PBRMaterial.prototype, "opacityTexture", void 0);
  31442. __decorate([
  31443. BABYLON.serializeAsTexture(),
  31444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31445. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  31446. __decorate([
  31447. BABYLON.serializeAsTexture(),
  31448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31449. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  31450. __decorate([
  31451. BABYLON.serializeAsTexture(),
  31452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31453. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  31454. __decorate([
  31455. BABYLON.serializeAsTexture(),
  31456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31457. ], PBRMaterial.prototype, "metallicTexture", void 0);
  31458. __decorate([
  31459. BABYLON.serialize(),
  31460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31461. ], PBRMaterial.prototype, "metallic", void 0);
  31462. __decorate([
  31463. BABYLON.serialize(),
  31464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31465. ], PBRMaterial.prototype, "roughness", void 0);
  31466. __decorate([
  31467. BABYLON.serializeAsTexture(),
  31468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31469. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  31470. __decorate([
  31471. BABYLON.serializeAsTexture(),
  31472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31473. ], PBRMaterial.prototype, "bumpTexture", void 0);
  31474. __decorate([
  31475. BABYLON.serializeAsTexture(),
  31476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  31477. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  31478. __decorate([
  31479. BABYLON.serializeAsTexture(),
  31480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31481. ], PBRMaterial.prototype, "refractionTexture", void 0);
  31482. __decorate([
  31483. BABYLON.serializeAsColor3("ambient"),
  31484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31485. ], PBRMaterial.prototype, "ambientColor", void 0);
  31486. __decorate([
  31487. BABYLON.serializeAsColor3("albedo"),
  31488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31489. ], PBRMaterial.prototype, "albedoColor", void 0);
  31490. __decorate([
  31491. BABYLON.serializeAsColor3("reflectivity"),
  31492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31493. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  31494. __decorate([
  31495. BABYLON.serializeAsColor3("reflection"),
  31496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31497. ], PBRMaterial.prototype, "reflectionColor", void 0);
  31498. __decorate([
  31499. BABYLON.serializeAsColor3("emissive"),
  31500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31501. ], PBRMaterial.prototype, "emissiveColor", void 0);
  31502. __decorate([
  31503. BABYLON.serialize(),
  31504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31505. ], PBRMaterial.prototype, "microSurface", void 0);
  31506. __decorate([
  31507. BABYLON.serialize(),
  31508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31509. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  31510. __decorate([
  31511. BABYLON.serialize(),
  31512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31513. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  31514. __decorate([
  31515. BABYLON.serialize(),
  31516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31517. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  31518. __decorate([
  31519. BABYLON.serialize(),
  31520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31521. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31522. __decorate([
  31523. BABYLON.serialize(),
  31524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31525. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  31526. __decorate([
  31527. BABYLON.serialize(),
  31528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31529. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  31530. __decorate([
  31531. BABYLON.serialize(),
  31532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31533. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  31534. __decorate([
  31535. BABYLON.serialize(),
  31536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31537. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  31538. __decorate([
  31539. BABYLON.serialize(),
  31540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31541. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  31542. __decorate([
  31543. BABYLON.serialize(),
  31544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31545. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  31546. __decorate([
  31547. BABYLON.serialize(),
  31548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31549. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  31550. __decorate([
  31551. BABYLON.serialize(),
  31552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31553. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  31554. __decorate([
  31555. BABYLON.serialize(),
  31556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31557. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  31558. __decorate([
  31559. BABYLON.serialize(),
  31560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31561. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  31562. __decorate([
  31563. BABYLON.serialize(),
  31564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31565. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  31566. __decorate([
  31567. BABYLON.serialize(),
  31568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31569. ], PBRMaterial.prototype, "useParallax", void 0);
  31570. __decorate([
  31571. BABYLON.serialize(),
  31572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31573. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  31574. __decorate([
  31575. BABYLON.serialize(),
  31576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31577. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  31578. __decorate([
  31579. BABYLON.serialize(),
  31580. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31581. ], PBRMaterial.prototype, "disableLighting", void 0);
  31582. __decorate([
  31583. BABYLON.serialize(),
  31584. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31585. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  31586. __decorate([
  31587. BABYLON.serialize(),
  31588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31589. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  31590. __decorate([
  31591. BABYLON.serialize(),
  31592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31593. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  31594. __decorate([
  31595. BABYLON.serialize(),
  31596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31597. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  31598. __decorate([
  31599. BABYLON.serialize(),
  31600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31601. ], PBRMaterial.prototype, "premultiplyAlpha", void 0);
  31602. __decorate([
  31603. BABYLON.serialize(),
  31604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31605. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  31606. BABYLON.PBRMaterial = PBRMaterial;
  31607. })(BABYLON || (BABYLON = {}));
  31608. //# sourceMappingURL=babylon.pbrMaterial.js.map
  31609. var BABYLON;
  31610. (function (BABYLON) {
  31611. /**
  31612. * The PBR material of BJS following the metal roughness convention.
  31613. *
  31614. * This fits to the define PBR convention in the GLTF definition:
  31615. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  31616. */
  31617. var PBRMetallicRoughnessMaterial = (function (_super) {
  31618. __extends(PBRMetallicRoughnessMaterial, _super);
  31619. /**
  31620. * Instantiates a new PBRMetalRoughnessMaterial instance.
  31621. *
  31622. * @param name The material name
  31623. * @param scene The scene the material will be use in.
  31624. */
  31625. function PBRMetallicRoughnessMaterial(name, scene) {
  31626. var _this = _super.call(this, name, scene) || this;
  31627. _this._useRoughnessFromMetallicTextureGreen = true;
  31628. _this._useMetallnessFromMetallicTextureBlue = true;
  31629. return _this;
  31630. }
  31631. /**
  31632. * Return the currrent class name of the material.
  31633. */
  31634. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  31635. return "PBRMetallicRoughnessMaterial";
  31636. };
  31637. /**
  31638. * Return the active textures of the material.
  31639. */
  31640. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  31641. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31642. if (this.baseTexture) {
  31643. activeTextures.push(this.baseTexture);
  31644. }
  31645. if (this.metallicRoughnessTexture) {
  31646. activeTextures.push(this.metallicRoughnessTexture);
  31647. }
  31648. return activeTextures;
  31649. };
  31650. /**
  31651. * Serialize the material to a parsable JSON object.
  31652. */
  31653. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  31654. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31655. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  31656. return serializationObject;
  31657. };
  31658. /**
  31659. * Parses a JSON object correponding to the serialize function.
  31660. */
  31661. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  31662. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  31663. };
  31664. return PBRMetallicRoughnessMaterial;
  31665. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  31666. __decorate([
  31667. BABYLON.serializeAsTexture(),
  31668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  31669. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  31670. __decorate([
  31671. BABYLON.serializeAsTexture(),
  31672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  31673. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  31674. __decorate([
  31675. BABYLON.serialize(),
  31676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31677. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  31678. __decorate([
  31679. BABYLON.serialize(),
  31680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31681. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  31682. __decorate([
  31683. BABYLON.serializeAsTexture(),
  31684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  31685. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  31686. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  31687. })(BABYLON || (BABYLON = {}));
  31688. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  31689. var BABYLON;
  31690. (function (BABYLON) {
  31691. /**
  31692. * The PBR material of BJS following the specular glossiness convention.
  31693. *
  31694. * This fits to the define PBR convention in the GLTF definition:
  31695. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  31696. */
  31697. var PBRSpecularGlossinessMaterial = (function (_super) {
  31698. __extends(PBRSpecularGlossinessMaterial, _super);
  31699. /**
  31700. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  31701. *
  31702. * @param name The material name
  31703. * @param scene The scene the material will be use in.
  31704. */
  31705. function PBRSpecularGlossinessMaterial(name, scene) {
  31706. var _this = _super.call(this, name, scene) || this;
  31707. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  31708. return _this;
  31709. }
  31710. /**
  31711. * Return the currrent class name of the material.
  31712. */
  31713. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  31714. return "PBRSpecularGlossinessMaterial";
  31715. };
  31716. /**
  31717. * Return the active textures of the material.
  31718. */
  31719. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  31720. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31721. if (this.diffuseTexture) {
  31722. activeTextures.push(this.diffuseTexture);
  31723. }
  31724. if (this.specularGlossinessTexture) {
  31725. activeTextures.push(this.specularGlossinessTexture);
  31726. }
  31727. return activeTextures;
  31728. };
  31729. /**
  31730. * Serialize the material to a parsable JSON object.
  31731. */
  31732. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  31733. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31734. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  31735. return serializationObject;
  31736. };
  31737. /**
  31738. * Parses a JSON object correponding to the serialize function.
  31739. */
  31740. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  31741. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  31742. };
  31743. return PBRSpecularGlossinessMaterial;
  31744. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  31745. __decorate([
  31746. BABYLON.serializeAsColor3(),
  31747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  31748. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  31749. __decorate([
  31750. BABYLON.serializeAsTexture(),
  31751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  31752. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  31753. __decorate([
  31754. BABYLON.serializeAsColor3(),
  31755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  31756. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  31757. __decorate([
  31758. BABYLON.serialize(),
  31759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  31760. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  31761. __decorate([
  31762. BABYLON.serializeAsTexture(),
  31763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  31764. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  31765. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  31766. })(BABYLON || (BABYLON = {}));
  31767. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  31768. var BABYLON;
  31769. (function (BABYLON) {
  31770. BABYLON.CameraInputTypes = {};
  31771. var CameraInputsManager = (function () {
  31772. function CameraInputsManager(camera) {
  31773. this.attached = {};
  31774. this.camera = camera;
  31775. this.checkInputs = function () { };
  31776. }
  31777. CameraInputsManager.prototype.add = function (input) {
  31778. var type = input.getSimpleName();
  31779. if (this.attached[type]) {
  31780. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  31781. return;
  31782. }
  31783. this.attached[type] = input;
  31784. input.camera = this.camera;
  31785. //for checkInputs, we are dynamically creating a function
  31786. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  31787. if (input.checkInputs) {
  31788. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31789. }
  31790. if (this.attachedElement) {
  31791. input.attachControl(this.attachedElement);
  31792. }
  31793. };
  31794. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31795. for (var cam in this.attached) {
  31796. var input = this.attached[cam];
  31797. if (input === inputToRemove) {
  31798. input.detachControl(this.attachedElement);
  31799. delete this.attached[cam];
  31800. this.rebuildInputCheck();
  31801. }
  31802. }
  31803. };
  31804. CameraInputsManager.prototype.removeByType = function (inputType) {
  31805. for (var cam in this.attached) {
  31806. var input = this.attached[cam];
  31807. if (input.getTypeName() === inputType) {
  31808. input.detachControl(this.attachedElement);
  31809. delete this.attached[cam];
  31810. this.rebuildInputCheck();
  31811. }
  31812. }
  31813. };
  31814. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31815. var current = this.checkInputs;
  31816. return function () {
  31817. current();
  31818. fn();
  31819. };
  31820. };
  31821. CameraInputsManager.prototype.attachInput = function (input) {
  31822. input.attachControl(this.attachedElement, this.noPreventDefault);
  31823. };
  31824. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31825. if (this.attachedElement) {
  31826. return;
  31827. }
  31828. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31829. this.attachedElement = element;
  31830. this.noPreventDefault = noPreventDefault;
  31831. for (var cam in this.attached) {
  31832. var input = this.attached[cam];
  31833. this.attached[cam].attachControl(element, noPreventDefault);
  31834. }
  31835. };
  31836. CameraInputsManager.prototype.detachElement = function (element) {
  31837. if (this.attachedElement !== element) {
  31838. return;
  31839. }
  31840. for (var cam in this.attached) {
  31841. var input = this.attached[cam];
  31842. this.attached[cam].detachControl(element);
  31843. }
  31844. this.attachedElement = null;
  31845. };
  31846. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31847. this.checkInputs = function () { };
  31848. for (var cam in this.attached) {
  31849. var input = this.attached[cam];
  31850. if (input.checkInputs) {
  31851. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31852. }
  31853. }
  31854. };
  31855. CameraInputsManager.prototype.clear = function () {
  31856. if (this.attachedElement) {
  31857. this.detachElement(this.attachedElement);
  31858. }
  31859. this.attached = {};
  31860. this.attachedElement = null;
  31861. this.checkInputs = function () { };
  31862. };
  31863. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31864. var inputs = {};
  31865. for (var cam in this.attached) {
  31866. var input = this.attached[cam];
  31867. var res = BABYLON.SerializationHelper.Serialize(input);
  31868. inputs[input.getTypeName()] = res;
  31869. }
  31870. serializedCamera.inputsmgr = inputs;
  31871. };
  31872. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31873. var parsedInputs = parsedCamera.inputsmgr;
  31874. if (parsedInputs) {
  31875. this.clear();
  31876. for (var n in parsedInputs) {
  31877. var construct = BABYLON.CameraInputTypes[n];
  31878. if (construct) {
  31879. var parsedinput = parsedInputs[n];
  31880. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31881. this.add(input);
  31882. }
  31883. }
  31884. }
  31885. else {
  31886. //2016-03-08 this part is for managing backward compatibility
  31887. for (var n in this.attached) {
  31888. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  31889. if (construct) {
  31890. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31891. this.remove(this.attached[n]);
  31892. this.add(input);
  31893. }
  31894. }
  31895. }
  31896. };
  31897. return CameraInputsManager;
  31898. }());
  31899. BABYLON.CameraInputsManager = CameraInputsManager;
  31900. })(BABYLON || (BABYLON = {}));
  31901. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31902. var BABYLON;
  31903. (function (BABYLON) {
  31904. var FreeCameraMouseInput = (function () {
  31905. function FreeCameraMouseInput(touchEnabled) {
  31906. if (touchEnabled === void 0) { touchEnabled = true; }
  31907. this.touchEnabled = touchEnabled;
  31908. this.buttons = [0, 1, 2];
  31909. this.angularSensibility = 2000.0;
  31910. }
  31911. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  31912. var _this = this;
  31913. var engine = this.camera.getEngine();
  31914. if (!this._pointerInput) {
  31915. this._pointerInput = function (p, s) {
  31916. var evt = p.event;
  31917. if (!_this.touchEnabled && evt.pointerType === "touch") {
  31918. return;
  31919. }
  31920. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31921. return;
  31922. }
  31923. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31924. try {
  31925. evt.srcElement.setPointerCapture(evt.pointerId);
  31926. }
  31927. catch (e) {
  31928. //Nothing to do with the error. Execution will continue.
  31929. }
  31930. _this.previousPosition = {
  31931. x: evt.clientX,
  31932. y: evt.clientY
  31933. };
  31934. if (!noPreventDefault) {
  31935. evt.preventDefault();
  31936. element.focus();
  31937. }
  31938. }
  31939. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  31940. try {
  31941. evt.srcElement.releasePointerCapture(evt.pointerId);
  31942. }
  31943. catch (e) {
  31944. //Nothing to do with the error.
  31945. }
  31946. _this.previousPosition = null;
  31947. if (!noPreventDefault) {
  31948. evt.preventDefault();
  31949. }
  31950. }
  31951. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  31952. if (!_this.previousPosition || engine.isPointerLock) {
  31953. return;
  31954. }
  31955. var offsetX = evt.clientX - _this.previousPosition.x;
  31956. var offsetY = evt.clientY - _this.previousPosition.y;
  31957. if (_this.camera.getScene().useRightHandedSystem) {
  31958. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  31959. }
  31960. else {
  31961. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  31962. }
  31963. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  31964. _this.previousPosition = {
  31965. x: evt.clientX,
  31966. y: evt.clientY
  31967. };
  31968. if (!noPreventDefault) {
  31969. evt.preventDefault();
  31970. }
  31971. }
  31972. };
  31973. }
  31974. this._onMouseMove = function (evt) {
  31975. if (!engine.isPointerLock) {
  31976. return;
  31977. }
  31978. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  31979. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  31980. if (_this.camera.getScene().useRightHandedSystem) {
  31981. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  31982. }
  31983. else {
  31984. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  31985. }
  31986. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  31987. _this.previousPosition = null;
  31988. if (!noPreventDefault) {
  31989. evt.preventDefault();
  31990. }
  31991. };
  31992. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  31993. element.addEventListener("mousemove", this._onMouseMove, false);
  31994. };
  31995. FreeCameraMouseInput.prototype.detachControl = function (element) {
  31996. if (this._observer && element) {
  31997. this.camera.getScene().onPointerObservable.remove(this._observer);
  31998. element.removeEventListener("mousemove", this._onMouseMove);
  31999. this._observer = null;
  32000. this._onMouseMove = null;
  32001. this.previousPosition = null;
  32002. }
  32003. };
  32004. FreeCameraMouseInput.prototype.getTypeName = function () {
  32005. return "FreeCameraMouseInput";
  32006. };
  32007. FreeCameraMouseInput.prototype.getSimpleName = function () {
  32008. return "mouse";
  32009. };
  32010. return FreeCameraMouseInput;
  32011. }());
  32012. __decorate([
  32013. BABYLON.serialize()
  32014. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  32015. __decorate([
  32016. BABYLON.serialize()
  32017. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  32018. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  32019. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  32020. })(BABYLON || (BABYLON = {}));
  32021. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  32022. var BABYLON;
  32023. (function (BABYLON) {
  32024. var FreeCameraKeyboardMoveInput = (function () {
  32025. function FreeCameraKeyboardMoveInput() {
  32026. this._keys = [];
  32027. this.keysUp = [38];
  32028. this.keysDown = [40];
  32029. this.keysLeft = [37];
  32030. this.keysRight = [39];
  32031. }
  32032. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  32033. var _this = this;
  32034. if (!this._onKeyDown) {
  32035. element.tabIndex = 1;
  32036. this._onKeyDown = function (evt) {
  32037. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32038. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32039. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32040. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32041. var index = _this._keys.indexOf(evt.keyCode);
  32042. if (index === -1) {
  32043. _this._keys.push(evt.keyCode);
  32044. }
  32045. if (!noPreventDefault) {
  32046. evt.preventDefault();
  32047. }
  32048. }
  32049. };
  32050. this._onKeyUp = function (evt) {
  32051. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32052. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32053. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32054. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32055. var index = _this._keys.indexOf(evt.keyCode);
  32056. if (index >= 0) {
  32057. _this._keys.splice(index, 1);
  32058. }
  32059. if (!noPreventDefault) {
  32060. evt.preventDefault();
  32061. }
  32062. }
  32063. };
  32064. element.addEventListener("keydown", this._onKeyDown, false);
  32065. element.addEventListener("keyup", this._onKeyUp, false);
  32066. BABYLON.Tools.RegisterTopRootEvents([
  32067. { name: "blur", handler: this._onLostFocus }
  32068. ]);
  32069. }
  32070. };
  32071. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  32072. if (this._onKeyDown) {
  32073. element.removeEventListener("keydown", this._onKeyDown);
  32074. element.removeEventListener("keyup", this._onKeyUp);
  32075. BABYLON.Tools.UnregisterTopRootEvents([
  32076. { name: "blur", handler: this._onLostFocus }
  32077. ]);
  32078. this._keys = [];
  32079. this._onKeyDown = null;
  32080. this._onKeyUp = null;
  32081. }
  32082. };
  32083. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  32084. if (this._onKeyDown) {
  32085. var camera = this.camera;
  32086. // Keyboard
  32087. for (var index = 0; index < this._keys.length; index++) {
  32088. var keyCode = this._keys[index];
  32089. var speed = camera._computeLocalCameraSpeed();
  32090. if (this.keysLeft.indexOf(keyCode) !== -1) {
  32091. camera._localDirection.copyFromFloats(-speed, 0, 0);
  32092. }
  32093. else if (this.keysUp.indexOf(keyCode) !== -1) {
  32094. camera._localDirection.copyFromFloats(0, 0, speed);
  32095. }
  32096. else if (this.keysRight.indexOf(keyCode) !== -1) {
  32097. camera._localDirection.copyFromFloats(speed, 0, 0);
  32098. }
  32099. else if (this.keysDown.indexOf(keyCode) !== -1) {
  32100. camera._localDirection.copyFromFloats(0, 0, -speed);
  32101. }
  32102. if (camera.getScene().useRightHandedSystem) {
  32103. camera._localDirection.z *= -1;
  32104. }
  32105. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  32106. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  32107. camera.cameraDirection.addInPlace(camera._transformedDirection);
  32108. }
  32109. }
  32110. };
  32111. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  32112. return "FreeCameraKeyboardMoveInput";
  32113. };
  32114. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  32115. this._keys = [];
  32116. };
  32117. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  32118. return "keyboard";
  32119. };
  32120. return FreeCameraKeyboardMoveInput;
  32121. }());
  32122. __decorate([
  32123. BABYLON.serialize()
  32124. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  32125. __decorate([
  32126. BABYLON.serialize()
  32127. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  32128. __decorate([
  32129. BABYLON.serialize()
  32130. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  32131. __decorate([
  32132. BABYLON.serialize()
  32133. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  32134. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  32135. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  32136. })(BABYLON || (BABYLON = {}));
  32137. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  32138. var BABYLON;
  32139. (function (BABYLON) {
  32140. var FreeCameraInputsManager = (function (_super) {
  32141. __extends(FreeCameraInputsManager, _super);
  32142. function FreeCameraInputsManager(camera) {
  32143. return _super.call(this, camera) || this;
  32144. }
  32145. FreeCameraInputsManager.prototype.addKeyboard = function () {
  32146. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  32147. return this;
  32148. };
  32149. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  32150. if (touchEnabled === void 0) { touchEnabled = true; }
  32151. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  32152. return this;
  32153. };
  32154. FreeCameraInputsManager.prototype.addGamepad = function () {
  32155. this.add(new BABYLON.FreeCameraGamepadInput());
  32156. return this;
  32157. };
  32158. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  32159. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  32160. return this;
  32161. };
  32162. FreeCameraInputsManager.prototype.addTouch = function () {
  32163. this.add(new BABYLON.FreeCameraTouchInput());
  32164. return this;
  32165. };
  32166. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  32167. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  32168. return this;
  32169. };
  32170. return FreeCameraInputsManager;
  32171. }(BABYLON.CameraInputsManager));
  32172. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  32173. })(BABYLON || (BABYLON = {}));
  32174. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  32175. /// <reference path="babylon.camera.ts" />
  32176. var BABYLON;
  32177. (function (BABYLON) {
  32178. var TargetCamera = (function (_super) {
  32179. __extends(TargetCamera, _super);
  32180. function TargetCamera(name, position, scene) {
  32181. var _this = _super.call(this, name, position, scene) || this;
  32182. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  32183. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  32184. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  32185. _this.speed = 2.0;
  32186. _this.noRotationConstraint = false;
  32187. _this.lockedTarget = null;
  32188. _this._currentTarget = BABYLON.Vector3.Zero();
  32189. _this._viewMatrix = BABYLON.Matrix.Zero();
  32190. _this._camMatrix = BABYLON.Matrix.Zero();
  32191. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  32192. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  32193. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  32194. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  32195. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  32196. _this._lookAtTemp = BABYLON.Matrix.Zero();
  32197. _this._tempMatrix = BABYLON.Matrix.Zero();
  32198. return _this;
  32199. }
  32200. TargetCamera.prototype.getFrontPosition = function (distance) {
  32201. var direction = this.getTarget().subtract(this.position);
  32202. direction.normalize();
  32203. direction.scaleInPlace(distance);
  32204. return this.globalPosition.add(direction);
  32205. };
  32206. TargetCamera.prototype._getLockedTargetPosition = function () {
  32207. if (!this.lockedTarget) {
  32208. return null;
  32209. }
  32210. if (this.lockedTarget.absolutePosition) {
  32211. this.lockedTarget.computeWorldMatrix();
  32212. }
  32213. return this.lockedTarget.absolutePosition || this.lockedTarget;
  32214. };
  32215. // Cache
  32216. TargetCamera.prototype._initCache = function () {
  32217. _super.prototype._initCache.call(this);
  32218. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32219. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32220. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32221. };
  32222. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  32223. if (!ignoreParentClass) {
  32224. _super.prototype._updateCache.call(this);
  32225. }
  32226. var lockedTargetPosition = this._getLockedTargetPosition();
  32227. if (!lockedTargetPosition) {
  32228. this._cache.lockedTarget = null;
  32229. }
  32230. else {
  32231. if (!this._cache.lockedTarget) {
  32232. this._cache.lockedTarget = lockedTargetPosition.clone();
  32233. }
  32234. else {
  32235. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  32236. }
  32237. }
  32238. this._cache.rotation.copyFrom(this.rotation);
  32239. if (this.rotationQuaternion)
  32240. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  32241. };
  32242. // Synchronized
  32243. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  32244. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  32245. return false;
  32246. }
  32247. var lockedTargetPosition = this._getLockedTargetPosition();
  32248. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  32249. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  32250. };
  32251. // Methods
  32252. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  32253. var engine = this.getEngine();
  32254. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  32255. };
  32256. // Target
  32257. TargetCamera.prototype.setTarget = function (target) {
  32258. this.upVector.normalize();
  32259. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  32260. this._camMatrix.invert();
  32261. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  32262. var vDir = target.subtract(this.position);
  32263. if (vDir.x >= 0.0) {
  32264. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  32265. }
  32266. else {
  32267. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  32268. }
  32269. this.rotation.z = 0;
  32270. if (isNaN(this.rotation.x)) {
  32271. this.rotation.x = 0;
  32272. }
  32273. if (isNaN(this.rotation.y)) {
  32274. this.rotation.y = 0;
  32275. }
  32276. if (isNaN(this.rotation.z)) {
  32277. this.rotation.z = 0;
  32278. }
  32279. if (this.rotationQuaternion) {
  32280. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  32281. }
  32282. };
  32283. /**
  32284. * Return the current target position of the camera. This value is expressed in local space.
  32285. */
  32286. TargetCamera.prototype.getTarget = function () {
  32287. return this._currentTarget;
  32288. };
  32289. TargetCamera.prototype._decideIfNeedsToMove = function () {
  32290. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  32291. };
  32292. TargetCamera.prototype._updatePosition = function () {
  32293. if (this.parent) {
  32294. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  32295. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  32296. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  32297. return;
  32298. }
  32299. this.position.addInPlace(this.cameraDirection);
  32300. };
  32301. TargetCamera.prototype._checkInputs = function () {
  32302. var needToMove = this._decideIfNeedsToMove();
  32303. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  32304. // Move
  32305. if (needToMove) {
  32306. this._updatePosition();
  32307. }
  32308. // Rotate
  32309. if (needToRotate) {
  32310. this.rotation.x += this.cameraRotation.x;
  32311. this.rotation.y += this.cameraRotation.y;
  32312. //rotate, if quaternion is set and rotation was used
  32313. if (this.rotationQuaternion) {
  32314. var len = this.rotation.lengthSquared();
  32315. if (len) {
  32316. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  32317. }
  32318. }
  32319. if (!this.noRotationConstraint) {
  32320. var limit = (Math.PI / 2) * 0.95;
  32321. if (this.rotation.x > limit)
  32322. this.rotation.x = limit;
  32323. if (this.rotation.x < -limit)
  32324. this.rotation.x = -limit;
  32325. }
  32326. }
  32327. // Inertia
  32328. if (needToMove) {
  32329. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  32330. this.cameraDirection.x = 0;
  32331. }
  32332. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  32333. this.cameraDirection.y = 0;
  32334. }
  32335. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  32336. this.cameraDirection.z = 0;
  32337. }
  32338. this.cameraDirection.scaleInPlace(this.inertia);
  32339. }
  32340. if (needToRotate) {
  32341. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  32342. this.cameraRotation.x = 0;
  32343. }
  32344. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  32345. this.cameraRotation.y = 0;
  32346. }
  32347. this.cameraRotation.scaleInPlace(this.inertia);
  32348. }
  32349. _super.prototype._checkInputs.call(this);
  32350. };
  32351. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  32352. if (this.rotationQuaternion) {
  32353. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  32354. //update the up vector!
  32355. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  32356. }
  32357. else {
  32358. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  32359. }
  32360. };
  32361. TargetCamera.prototype._getViewMatrix = function () {
  32362. if (!this.lockedTarget) {
  32363. // Compute
  32364. this._updateCameraRotationMatrix();
  32365. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  32366. // Computing target and final matrix
  32367. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  32368. }
  32369. else {
  32370. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  32371. }
  32372. if (this.getScene().useRightHandedSystem) {
  32373. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  32374. }
  32375. else {
  32376. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  32377. }
  32378. return this._viewMatrix;
  32379. };
  32380. /**
  32381. * @override
  32382. * Override Camera.createRigCamera
  32383. */
  32384. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32385. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  32386. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  32387. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  32388. if (!this.rotationQuaternion) {
  32389. this.rotationQuaternion = new BABYLON.Quaternion();
  32390. }
  32391. rigCamera._cameraRigParams = {};
  32392. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  32393. }
  32394. return rigCamera;
  32395. }
  32396. return null;
  32397. };
  32398. /**
  32399. * @override
  32400. * Override Camera._updateRigCameras
  32401. */
  32402. TargetCamera.prototype._updateRigCameras = function () {
  32403. var camLeft = this._rigCameras[0];
  32404. var camRight = this._rigCameras[1];
  32405. switch (this.cameraRigMode) {
  32406. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32407. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32408. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32409. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32410. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  32411. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  32412. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  32413. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  32414. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  32415. camLeft.setTarget(this.getTarget());
  32416. camRight.setTarget(this.getTarget());
  32417. break;
  32418. case BABYLON.Camera.RIG_MODE_VR:
  32419. if (camLeft.rotationQuaternion) {
  32420. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  32421. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  32422. }
  32423. else {
  32424. camLeft.rotation.copyFrom(this.rotation);
  32425. camRight.rotation.copyFrom(this.rotation);
  32426. }
  32427. camLeft.position.copyFrom(this.position);
  32428. camRight.position.copyFrom(this.position);
  32429. break;
  32430. }
  32431. _super.prototype._updateRigCameras.call(this);
  32432. };
  32433. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  32434. if (!this._rigCamTransformMatrix) {
  32435. this._rigCamTransformMatrix = new BABYLON.Matrix();
  32436. }
  32437. var target = this.getTarget();
  32438. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  32439. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  32440. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  32441. };
  32442. TargetCamera.prototype.getClassName = function () {
  32443. return "TargetCamera";
  32444. };
  32445. return TargetCamera;
  32446. }(BABYLON.Camera));
  32447. __decorate([
  32448. BABYLON.serializeAsVector3()
  32449. ], TargetCamera.prototype, "rotation", void 0);
  32450. __decorate([
  32451. BABYLON.serialize()
  32452. ], TargetCamera.prototype, "speed", void 0);
  32453. __decorate([
  32454. BABYLON.serializeAsMeshReference("lockedTargetId")
  32455. ], TargetCamera.prototype, "lockedTarget", void 0);
  32456. BABYLON.TargetCamera = TargetCamera;
  32457. })(BABYLON || (BABYLON = {}));
  32458. //# sourceMappingURL=babylon.targetCamera.js.map
  32459. var BABYLON;
  32460. (function (BABYLON) {
  32461. var FreeCamera = (function (_super) {
  32462. __extends(FreeCamera, _super);
  32463. function FreeCamera(name, position, scene) {
  32464. var _this = _super.call(this, name, position, scene) || this;
  32465. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  32466. _this.checkCollisions = false;
  32467. _this.applyGravity = false;
  32468. _this._needMoveForGravity = false;
  32469. _this._oldPosition = BABYLON.Vector3.Zero();
  32470. _this._diffPosition = BABYLON.Vector3.Zero();
  32471. _this._newPosition = BABYLON.Vector3.Zero();
  32472. // Collisions
  32473. _this._collisionMask = -1;
  32474. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32475. if (collidedMesh === void 0) { collidedMesh = null; }
  32476. //TODO move this to the collision coordinator!
  32477. if (_this.getScene().workerCollisions)
  32478. newPosition.multiplyInPlace(_this._collider.radius);
  32479. var updatePosition = function (newPos) {
  32480. _this._newPosition.copyFrom(newPos);
  32481. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  32482. var oldPosition = _this.position.clone();
  32483. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  32484. _this.position.addInPlace(_this._diffPosition);
  32485. if (_this.onCollide && collidedMesh) {
  32486. _this.onCollide(collidedMesh);
  32487. }
  32488. }
  32489. };
  32490. updatePosition(newPosition);
  32491. };
  32492. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  32493. _this.inputs.addKeyboard().addMouse();
  32494. return _this;
  32495. }
  32496. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  32497. //-- begin properties for backward compatibility for inputs
  32498. get: function () {
  32499. var mouse = this.inputs.attached["mouse"];
  32500. if (mouse)
  32501. return mouse.angularSensibility;
  32502. },
  32503. set: function (value) {
  32504. var mouse = this.inputs.attached["mouse"];
  32505. if (mouse)
  32506. mouse.angularSensibility = value;
  32507. },
  32508. enumerable: true,
  32509. configurable: true
  32510. });
  32511. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  32512. get: function () {
  32513. var keyboard = this.inputs.attached["keyboard"];
  32514. if (keyboard)
  32515. return keyboard.keysUp;
  32516. },
  32517. set: function (value) {
  32518. var keyboard = this.inputs.attached["keyboard"];
  32519. if (keyboard)
  32520. keyboard.keysUp = value;
  32521. },
  32522. enumerable: true,
  32523. configurable: true
  32524. });
  32525. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  32526. get: function () {
  32527. var keyboard = this.inputs.attached["keyboard"];
  32528. if (keyboard)
  32529. return keyboard.keysDown;
  32530. },
  32531. set: function (value) {
  32532. var keyboard = this.inputs.attached["keyboard"];
  32533. if (keyboard)
  32534. keyboard.keysDown = value;
  32535. },
  32536. enumerable: true,
  32537. configurable: true
  32538. });
  32539. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  32540. get: function () {
  32541. var keyboard = this.inputs.attached["keyboard"];
  32542. if (keyboard)
  32543. return keyboard.keysLeft;
  32544. },
  32545. set: function (value) {
  32546. var keyboard = this.inputs.attached["keyboard"];
  32547. if (keyboard)
  32548. keyboard.keysLeft = value;
  32549. },
  32550. enumerable: true,
  32551. configurable: true
  32552. });
  32553. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  32554. get: function () {
  32555. var keyboard = this.inputs.attached["keyboard"];
  32556. if (keyboard)
  32557. return keyboard.keysRight;
  32558. },
  32559. set: function (value) {
  32560. var keyboard = this.inputs.attached["keyboard"];
  32561. if (keyboard)
  32562. keyboard.keysRight = value;
  32563. },
  32564. enumerable: true,
  32565. configurable: true
  32566. });
  32567. // Controls
  32568. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32569. this.inputs.attachElement(element, noPreventDefault);
  32570. };
  32571. FreeCamera.prototype.detachControl = function (element) {
  32572. this.inputs.detachElement(element);
  32573. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  32574. this.cameraRotation = new BABYLON.Vector2(0, 0);
  32575. };
  32576. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  32577. get: function () {
  32578. return this._collisionMask;
  32579. },
  32580. set: function (mask) {
  32581. this._collisionMask = !isNaN(mask) ? mask : -1;
  32582. },
  32583. enumerable: true,
  32584. configurable: true
  32585. });
  32586. FreeCamera.prototype._collideWithWorld = function (velocity) {
  32587. var globalPosition;
  32588. if (this.parent) {
  32589. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  32590. }
  32591. else {
  32592. globalPosition = this.position;
  32593. }
  32594. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  32595. if (!this._collider) {
  32596. this._collider = new BABYLON.Collider();
  32597. }
  32598. this._collider.radius = this.ellipsoid;
  32599. this._collider.collisionMask = this._collisionMask;
  32600. //no need for clone, as long as gravity is not on.
  32601. var actualVelocity = velocity;
  32602. //add gravity to the velocity to prevent the dual-collision checking
  32603. if (this.applyGravity) {
  32604. //this prevents mending with cameraDirection, a global variable of the free camera class.
  32605. actualVelocity = velocity.add(this.getScene().gravity);
  32606. }
  32607. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32608. };
  32609. FreeCamera.prototype._checkInputs = function () {
  32610. if (!this._localDirection) {
  32611. this._localDirection = BABYLON.Vector3.Zero();
  32612. this._transformedDirection = BABYLON.Vector3.Zero();
  32613. }
  32614. this.inputs.checkInputs();
  32615. _super.prototype._checkInputs.call(this);
  32616. };
  32617. FreeCamera.prototype._decideIfNeedsToMove = function () {
  32618. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  32619. };
  32620. FreeCamera.prototype._updatePosition = function () {
  32621. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  32622. this._collideWithWorld(this.cameraDirection);
  32623. }
  32624. else {
  32625. _super.prototype._updatePosition.call(this);
  32626. }
  32627. };
  32628. FreeCamera.prototype.dispose = function () {
  32629. this.inputs.clear();
  32630. _super.prototype.dispose.call(this);
  32631. };
  32632. FreeCamera.prototype.getClassName = function () {
  32633. return "FreeCamera";
  32634. };
  32635. return FreeCamera;
  32636. }(BABYLON.TargetCamera));
  32637. __decorate([
  32638. BABYLON.serializeAsVector3()
  32639. ], FreeCamera.prototype, "ellipsoid", void 0);
  32640. __decorate([
  32641. BABYLON.serialize()
  32642. ], FreeCamera.prototype, "checkCollisions", void 0);
  32643. __decorate([
  32644. BABYLON.serialize()
  32645. ], FreeCamera.prototype, "applyGravity", void 0);
  32646. BABYLON.FreeCamera = FreeCamera;
  32647. })(BABYLON || (BABYLON = {}));
  32648. //# sourceMappingURL=babylon.freeCamera.js.map
  32649. var BABYLON;
  32650. (function (BABYLON) {
  32651. var ArcRotateCameraKeyboardMoveInput = (function () {
  32652. function ArcRotateCameraKeyboardMoveInput() {
  32653. this._keys = [];
  32654. this.keysUp = [38];
  32655. this.keysDown = [40];
  32656. this.keysLeft = [37];
  32657. this.keysRight = [39];
  32658. }
  32659. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  32660. var _this = this;
  32661. element.tabIndex = 1;
  32662. this._onKeyDown = function (evt) {
  32663. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32664. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32665. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32666. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32667. var index = _this._keys.indexOf(evt.keyCode);
  32668. if (index === -1) {
  32669. _this._keys.push(evt.keyCode);
  32670. }
  32671. if (evt.preventDefault) {
  32672. if (!noPreventDefault) {
  32673. evt.preventDefault();
  32674. }
  32675. }
  32676. }
  32677. };
  32678. this._onKeyUp = function (evt) {
  32679. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32680. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32681. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32682. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32683. var index = _this._keys.indexOf(evt.keyCode);
  32684. if (index >= 0) {
  32685. _this._keys.splice(index, 1);
  32686. }
  32687. if (evt.preventDefault) {
  32688. if (!noPreventDefault) {
  32689. evt.preventDefault();
  32690. }
  32691. }
  32692. }
  32693. };
  32694. this._onLostFocus = function () {
  32695. _this._keys = [];
  32696. };
  32697. element.addEventListener("keydown", this._onKeyDown, false);
  32698. element.addEventListener("keyup", this._onKeyUp, false);
  32699. BABYLON.Tools.RegisterTopRootEvents([
  32700. { name: "blur", handler: this._onLostFocus }
  32701. ]);
  32702. };
  32703. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  32704. if (element) {
  32705. element.removeEventListener("keydown", this._onKeyDown);
  32706. element.removeEventListener("keyup", this._onKeyUp);
  32707. }
  32708. BABYLON.Tools.UnregisterTopRootEvents([
  32709. { name: "blur", handler: this._onLostFocus }
  32710. ]);
  32711. this._keys = [];
  32712. this._onKeyDown = null;
  32713. this._onKeyUp = null;
  32714. this._onLostFocus = null;
  32715. };
  32716. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  32717. if (this._onKeyDown) {
  32718. var camera = this.camera;
  32719. for (var index = 0; index < this._keys.length; index++) {
  32720. var keyCode = this._keys[index];
  32721. if (this.keysLeft.indexOf(keyCode) !== -1) {
  32722. camera.inertialAlphaOffset -= 0.01;
  32723. }
  32724. else if (this.keysUp.indexOf(keyCode) !== -1) {
  32725. camera.inertialBetaOffset -= 0.01;
  32726. }
  32727. else if (this.keysRight.indexOf(keyCode) !== -1) {
  32728. camera.inertialAlphaOffset += 0.01;
  32729. }
  32730. else if (this.keysDown.indexOf(keyCode) !== -1) {
  32731. camera.inertialBetaOffset += 0.01;
  32732. }
  32733. }
  32734. }
  32735. };
  32736. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  32737. return "ArcRotateCameraKeyboardMoveInput";
  32738. };
  32739. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  32740. return "keyboard";
  32741. };
  32742. return ArcRotateCameraKeyboardMoveInput;
  32743. }());
  32744. __decorate([
  32745. BABYLON.serialize()
  32746. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  32747. __decorate([
  32748. BABYLON.serialize()
  32749. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  32750. __decorate([
  32751. BABYLON.serialize()
  32752. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  32753. __decorate([
  32754. BABYLON.serialize()
  32755. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  32756. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  32757. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  32758. })(BABYLON || (BABYLON = {}));
  32759. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  32760. var BABYLON;
  32761. (function (BABYLON) {
  32762. var ArcRotateCameraMouseWheelInput = (function () {
  32763. function ArcRotateCameraMouseWheelInput() {
  32764. this.wheelPrecision = 3.0;
  32765. }
  32766. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  32767. var _this = this;
  32768. this._wheel = function (p, s) {
  32769. //sanity check - this should be a PointerWheel event.
  32770. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  32771. return;
  32772. var event = p.event;
  32773. var delta = 0;
  32774. if (event.wheelDelta) {
  32775. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  32776. }
  32777. else if (event.detail) {
  32778. delta = -event.detail / _this.wheelPrecision;
  32779. }
  32780. if (delta)
  32781. _this.camera.inertialRadiusOffset += delta;
  32782. if (event.preventDefault) {
  32783. if (!noPreventDefault) {
  32784. event.preventDefault();
  32785. }
  32786. }
  32787. };
  32788. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  32789. };
  32790. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  32791. if (this._observer && element) {
  32792. this.camera.getScene().onPointerObservable.remove(this._observer);
  32793. this._observer = null;
  32794. this._wheel = null;
  32795. }
  32796. };
  32797. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  32798. return "ArcRotateCameraMouseWheelInput";
  32799. };
  32800. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  32801. return "mousewheel";
  32802. };
  32803. return ArcRotateCameraMouseWheelInput;
  32804. }());
  32805. __decorate([
  32806. BABYLON.serialize()
  32807. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  32808. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  32809. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  32810. })(BABYLON || (BABYLON = {}));
  32811. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  32812. var BABYLON;
  32813. (function (BABYLON) {
  32814. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  32815. var ArcRotateCameraPointersInput = (function () {
  32816. function ArcRotateCameraPointersInput() {
  32817. this.buttons = [0, 1, 2];
  32818. this.angularSensibilityX = 1000.0;
  32819. this.angularSensibilityY = 1000.0;
  32820. this.pinchPrecision = 6.0;
  32821. this.panningSensibility = 50.0;
  32822. this._isPanClick = false;
  32823. this.pinchInwards = true;
  32824. }
  32825. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  32826. var _this = this;
  32827. var engine = this.camera.getEngine();
  32828. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  32829. var pointA, pointB;
  32830. var previousPinchDistance = 0;
  32831. this._pointerInput = function (p, s) {
  32832. var evt = p.event;
  32833. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  32834. return;
  32835. }
  32836. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  32837. try {
  32838. evt.srcElement.setPointerCapture(evt.pointerId);
  32839. }
  32840. catch (e) {
  32841. //Nothing to do with the error. Execution will continue.
  32842. }
  32843. // Manage panning with pan button click
  32844. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  32845. // manage pointers
  32846. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  32847. if (pointA === undefined) {
  32848. pointA = cacheSoloPointer;
  32849. }
  32850. else if (pointB === undefined) {
  32851. pointB = cacheSoloPointer;
  32852. }
  32853. if (!noPreventDefault) {
  32854. evt.preventDefault();
  32855. element.focus();
  32856. }
  32857. }
  32858. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  32859. try {
  32860. evt.srcElement.releasePointerCapture(evt.pointerId);
  32861. }
  32862. catch (e) {
  32863. //Nothing to do with the error.
  32864. }
  32865. cacheSoloPointer = null;
  32866. previousPinchDistance = 0;
  32867. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  32868. //but emptying completly pointers collection is required to fix a bug on iPhone :
  32869. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  32870. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  32871. pointA = pointB = undefined;
  32872. if (!noPreventDefault) {
  32873. evt.preventDefault();
  32874. }
  32875. }
  32876. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  32877. if (!noPreventDefault) {
  32878. evt.preventDefault();
  32879. }
  32880. // One button down
  32881. if (pointA && pointB === undefined) {
  32882. if (_this.panningSensibility !== 0 &&
  32883. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  32884. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  32885. _this.camera
  32886. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  32887. _this.camera
  32888. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  32889. }
  32890. else {
  32891. var offsetX = evt.clientX - cacheSoloPointer.x;
  32892. var offsetY = evt.clientY - cacheSoloPointer.y;
  32893. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32894. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32895. }
  32896. cacheSoloPointer.x = evt.clientX;
  32897. cacheSoloPointer.y = evt.clientY;
  32898. }
  32899. else if (pointA && pointB) {
  32900. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  32901. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  32902. ed.x = evt.clientX;
  32903. ed.y = evt.clientY;
  32904. var direction = _this.pinchInwards ? 1 : -1;
  32905. var distX = pointA.x - pointB.x;
  32906. var distY = pointA.y - pointB.y;
  32907. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  32908. if (previousPinchDistance === 0) {
  32909. previousPinchDistance = pinchSquaredDistance;
  32910. return;
  32911. }
  32912. if (pinchSquaredDistance !== previousPinchDistance) {
  32913. _this.camera
  32914. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  32915. (_this.pinchPrecision *
  32916. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  32917. direction);
  32918. previousPinchDistance = pinchSquaredDistance;
  32919. }
  32920. }
  32921. }
  32922. };
  32923. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  32924. this._onContextMenu = function (evt) {
  32925. evt.preventDefault();
  32926. };
  32927. if (!this.camera._useCtrlForPanning) {
  32928. element.addEventListener("contextmenu", this._onContextMenu, false);
  32929. }
  32930. this._onLostFocus = function () {
  32931. //this._keys = [];
  32932. pointA = pointB = undefined;
  32933. previousPinchDistance = 0;
  32934. cacheSoloPointer = null;
  32935. };
  32936. this._onMouseMove = function (evt) {
  32937. if (!engine.isPointerLock) {
  32938. return;
  32939. }
  32940. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  32941. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  32942. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32943. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32944. if (!noPreventDefault) {
  32945. evt.preventDefault();
  32946. }
  32947. };
  32948. this._onGestureStart = function (e) {
  32949. if (window.MSGesture === undefined) {
  32950. return;
  32951. }
  32952. if (!_this._MSGestureHandler) {
  32953. _this._MSGestureHandler = new MSGesture();
  32954. _this._MSGestureHandler.target = element;
  32955. }
  32956. _this._MSGestureHandler.addPointer(e.pointerId);
  32957. };
  32958. this._onGesture = function (e) {
  32959. _this.camera.radius *= e.scale;
  32960. if (e.preventDefault) {
  32961. if (!noPreventDefault) {
  32962. e.stopPropagation();
  32963. e.preventDefault();
  32964. }
  32965. }
  32966. };
  32967. element.addEventListener("mousemove", this._onMouseMove, false);
  32968. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  32969. element.addEventListener("MSGestureChange", this._onGesture, false);
  32970. BABYLON.Tools.RegisterTopRootEvents([
  32971. { name: "blur", handler: this._onLostFocus }
  32972. ]);
  32973. };
  32974. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  32975. if (element && this._observer) {
  32976. this.camera.getScene().onPointerObservable.remove(this._observer);
  32977. this._observer = null;
  32978. element.removeEventListener("contextmenu", this._onContextMenu);
  32979. element.removeEventListener("mousemove", this._onMouseMove);
  32980. element.removeEventListener("MSPointerDown", this._onGestureStart);
  32981. element.removeEventListener("MSGestureChange", this._onGesture);
  32982. this._isPanClick = false;
  32983. this.pinchInwards = true;
  32984. this._onMouseMove = null;
  32985. this._onGestureStart = null;
  32986. this._onGesture = null;
  32987. this._MSGestureHandler = null;
  32988. this._onLostFocus = null;
  32989. this._onContextMenu = null;
  32990. }
  32991. BABYLON.Tools.UnregisterTopRootEvents([
  32992. { name: "blur", handler: this._onLostFocus }
  32993. ]);
  32994. };
  32995. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  32996. return "ArcRotateCameraPointersInput";
  32997. };
  32998. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  32999. return "pointers";
  33000. };
  33001. return ArcRotateCameraPointersInput;
  33002. }());
  33003. __decorate([
  33004. BABYLON.serialize()
  33005. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  33006. __decorate([
  33007. BABYLON.serialize()
  33008. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  33009. __decorate([
  33010. BABYLON.serialize()
  33011. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  33012. __decorate([
  33013. BABYLON.serialize()
  33014. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  33015. __decorate([
  33016. BABYLON.serialize()
  33017. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  33018. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  33019. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  33020. })(BABYLON || (BABYLON = {}));
  33021. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  33022. /// <reference path="babylon.targetCamera.ts" />
  33023. /// <reference path="..\Tools\babylon.tools.ts" />
  33024. var BABYLON;
  33025. (function (BABYLON) {
  33026. var ArcRotateCamera = (function (_super) {
  33027. __extends(ArcRotateCamera, _super);
  33028. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  33029. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  33030. _this.inertialAlphaOffset = 0;
  33031. _this.inertialBetaOffset = 0;
  33032. _this.inertialRadiusOffset = 0;
  33033. _this.lowerAlphaLimit = null;
  33034. _this.upperAlphaLimit = null;
  33035. _this.lowerBetaLimit = 0.01;
  33036. _this.upperBetaLimit = Math.PI;
  33037. _this.lowerRadiusLimit = null;
  33038. _this.upperRadiusLimit = null;
  33039. _this.inertialPanningX = 0;
  33040. _this.inertialPanningY = 0;
  33041. _this.panningInertia = 0.9;
  33042. //-- end properties for backward compatibility for inputs
  33043. _this.zoomOnFactor = 1;
  33044. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  33045. _this.allowUpsideDown = true;
  33046. _this._viewMatrix = new BABYLON.Matrix();
  33047. // Panning
  33048. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  33049. _this.checkCollisions = false;
  33050. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  33051. _this._previousPosition = BABYLON.Vector3.Zero();
  33052. _this._collisionVelocity = BABYLON.Vector3.Zero();
  33053. _this._newPosition = BABYLON.Vector3.Zero();
  33054. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  33055. if (collidedMesh === void 0) { collidedMesh = null; }
  33056. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  33057. newPosition.multiplyInPlace(_this._collider.radius);
  33058. }
  33059. if (!collidedMesh) {
  33060. _this._previousPosition.copyFrom(_this.position);
  33061. }
  33062. else {
  33063. _this.setPosition(newPosition);
  33064. if (_this.onCollide) {
  33065. _this.onCollide(collidedMesh);
  33066. }
  33067. }
  33068. // Recompute because of constraints
  33069. var cosa = Math.cos(_this.alpha);
  33070. var sina = Math.sin(_this.alpha);
  33071. var cosb = Math.cos(_this.beta);
  33072. var sinb = Math.sin(_this.beta);
  33073. if (sinb === 0) {
  33074. sinb = 0.0001;
  33075. }
  33076. var target = _this._getTargetPosition();
  33077. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  33078. _this.position.copyFrom(_this._newPosition);
  33079. var up = _this.upVector;
  33080. if (_this.allowUpsideDown && _this.beta < 0) {
  33081. up = up.clone();
  33082. up = up.negate();
  33083. }
  33084. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  33085. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  33086. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  33087. _this._collisionTriggered = false;
  33088. };
  33089. _this._target = BABYLON.Vector3.Zero();
  33090. if (target) {
  33091. _this.setTarget(target);
  33092. }
  33093. _this.alpha = alpha;
  33094. _this.beta = beta;
  33095. _this.radius = radius;
  33096. _this.getViewMatrix();
  33097. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  33098. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  33099. return _this;
  33100. }
  33101. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  33102. get: function () {
  33103. return this._target;
  33104. },
  33105. set: function (value) {
  33106. this.setTarget(value);
  33107. },
  33108. enumerable: true,
  33109. configurable: true
  33110. });
  33111. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  33112. //-- begin properties for backward compatibility for inputs
  33113. get: function () {
  33114. var pointers = this.inputs.attached["pointers"];
  33115. if (pointers)
  33116. return pointers.angularSensibilityX;
  33117. },
  33118. set: function (value) {
  33119. var pointers = this.inputs.attached["pointers"];
  33120. if (pointers) {
  33121. pointers.angularSensibilityX = value;
  33122. }
  33123. },
  33124. enumerable: true,
  33125. configurable: true
  33126. });
  33127. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  33128. get: function () {
  33129. var pointers = this.inputs.attached["pointers"];
  33130. if (pointers)
  33131. return pointers.angularSensibilityY;
  33132. },
  33133. set: function (value) {
  33134. var pointers = this.inputs.attached["pointers"];
  33135. if (pointers) {
  33136. pointers.angularSensibilityY = value;
  33137. }
  33138. },
  33139. enumerable: true,
  33140. configurable: true
  33141. });
  33142. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  33143. get: function () {
  33144. var pointers = this.inputs.attached["pointers"];
  33145. if (pointers)
  33146. return pointers.pinchPrecision;
  33147. },
  33148. set: function (value) {
  33149. var pointers = this.inputs.attached["pointers"];
  33150. if (pointers) {
  33151. pointers.pinchPrecision = value;
  33152. }
  33153. },
  33154. enumerable: true,
  33155. configurable: true
  33156. });
  33157. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  33158. get: function () {
  33159. var pointers = this.inputs.attached["pointers"];
  33160. if (pointers)
  33161. return pointers.panningSensibility;
  33162. },
  33163. set: function (value) {
  33164. var pointers = this.inputs.attached["pointers"];
  33165. if (pointers) {
  33166. pointers.panningSensibility = value;
  33167. }
  33168. },
  33169. enumerable: true,
  33170. configurable: true
  33171. });
  33172. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  33173. get: function () {
  33174. var keyboard = this.inputs.attached["keyboard"];
  33175. if (keyboard)
  33176. return keyboard.keysUp;
  33177. },
  33178. set: function (value) {
  33179. var keyboard = this.inputs.attached["keyboard"];
  33180. if (keyboard)
  33181. keyboard.keysUp = value;
  33182. },
  33183. enumerable: true,
  33184. configurable: true
  33185. });
  33186. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  33187. get: function () {
  33188. var keyboard = this.inputs.attached["keyboard"];
  33189. if (keyboard)
  33190. return keyboard.keysDown;
  33191. },
  33192. set: function (value) {
  33193. var keyboard = this.inputs.attached["keyboard"];
  33194. if (keyboard)
  33195. keyboard.keysDown = value;
  33196. },
  33197. enumerable: true,
  33198. configurable: true
  33199. });
  33200. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  33201. get: function () {
  33202. var keyboard = this.inputs.attached["keyboard"];
  33203. if (keyboard)
  33204. return keyboard.keysLeft;
  33205. },
  33206. set: function (value) {
  33207. var keyboard = this.inputs.attached["keyboard"];
  33208. if (keyboard)
  33209. keyboard.keysLeft = value;
  33210. },
  33211. enumerable: true,
  33212. configurable: true
  33213. });
  33214. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  33215. get: function () {
  33216. var keyboard = this.inputs.attached["keyboard"];
  33217. if (keyboard)
  33218. return keyboard.keysRight;
  33219. },
  33220. set: function (value) {
  33221. var keyboard = this.inputs.attached["keyboard"];
  33222. if (keyboard)
  33223. keyboard.keysRight = value;
  33224. },
  33225. enumerable: true,
  33226. configurable: true
  33227. });
  33228. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  33229. get: function () {
  33230. var mousewheel = this.inputs.attached["mousewheel"];
  33231. if (mousewheel)
  33232. return mousewheel.wheelPrecision;
  33233. },
  33234. set: function (value) {
  33235. var mousewheel = this.inputs.attached["mousewheel"];
  33236. if (mousewheel)
  33237. mousewheel.wheelPrecision = value;
  33238. },
  33239. enumerable: true,
  33240. configurable: true
  33241. });
  33242. // Cache
  33243. ArcRotateCamera.prototype._initCache = function () {
  33244. _super.prototype._initCache.call(this);
  33245. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  33246. this._cache.alpha = undefined;
  33247. this._cache.beta = undefined;
  33248. this._cache.radius = undefined;
  33249. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  33250. };
  33251. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  33252. if (!ignoreParentClass) {
  33253. _super.prototype._updateCache.call(this);
  33254. }
  33255. this._cache._target.copyFrom(this._getTargetPosition());
  33256. this._cache.alpha = this.alpha;
  33257. this._cache.beta = this.beta;
  33258. this._cache.radius = this.radius;
  33259. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  33260. };
  33261. ArcRotateCamera.prototype._getTargetPosition = function () {
  33262. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  33263. var pos = this._targetHost.getAbsolutePosition();
  33264. if (this._targetBoundingCenter) {
  33265. pos.addToRef(this._targetBoundingCenter, this._target);
  33266. }
  33267. else {
  33268. this._target.copyFrom(pos);
  33269. }
  33270. }
  33271. var lockedTargetPosition = this._getLockedTargetPosition();
  33272. if (lockedTargetPosition) {
  33273. return lockedTargetPosition;
  33274. }
  33275. return this._target;
  33276. };
  33277. // Synchronized
  33278. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  33279. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  33280. return false;
  33281. return this._cache._target.equals(this._getTargetPosition())
  33282. && this._cache.alpha === this.alpha
  33283. && this._cache.beta === this.beta
  33284. && this._cache.radius === this.radius
  33285. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  33286. };
  33287. // Methods
  33288. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  33289. var _this = this;
  33290. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  33291. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  33292. this._useCtrlForPanning = useCtrlForPanning;
  33293. this._panningMouseButton = panningMouseButton;
  33294. this.inputs.attachElement(element, noPreventDefault);
  33295. this._reset = function () {
  33296. _this.inertialAlphaOffset = 0;
  33297. _this.inertialBetaOffset = 0;
  33298. _this.inertialRadiusOffset = 0;
  33299. };
  33300. };
  33301. ArcRotateCamera.prototype.detachControl = function (element) {
  33302. this.inputs.detachElement(element);
  33303. if (this._reset) {
  33304. this._reset();
  33305. }
  33306. };
  33307. ArcRotateCamera.prototype._checkInputs = function () {
  33308. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  33309. if (this._collisionTriggered) {
  33310. return;
  33311. }
  33312. this.inputs.checkInputs();
  33313. // Inertia
  33314. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  33315. if (this.getScene().useRightHandedSystem) {
  33316. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  33317. }
  33318. else {
  33319. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  33320. }
  33321. this.beta += this.inertialBetaOffset;
  33322. this.radius -= this.inertialRadiusOffset;
  33323. this.inertialAlphaOffset *= this.inertia;
  33324. this.inertialBetaOffset *= this.inertia;
  33325. this.inertialRadiusOffset *= this.inertia;
  33326. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  33327. this.inertialAlphaOffset = 0;
  33328. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  33329. this.inertialBetaOffset = 0;
  33330. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  33331. this.inertialRadiusOffset = 0;
  33332. }
  33333. // Panning inertia
  33334. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  33335. if (!this._localDirection) {
  33336. this._localDirection = BABYLON.Vector3.Zero();
  33337. this._transformedDirection = BABYLON.Vector3.Zero();
  33338. }
  33339. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  33340. this._localDirection.multiplyInPlace(this.panningAxis);
  33341. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  33342. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  33343. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  33344. if (!this.panningAxis.y) {
  33345. this._transformedDirection.y = 0;
  33346. }
  33347. if (!this._targetHost) {
  33348. this._target.addInPlace(this._transformedDirection);
  33349. }
  33350. this.inertialPanningX *= this.panningInertia;
  33351. this.inertialPanningY *= this.panningInertia;
  33352. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  33353. this.inertialPanningX = 0;
  33354. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  33355. this.inertialPanningY = 0;
  33356. }
  33357. // Limits
  33358. this._checkLimits();
  33359. _super.prototype._checkInputs.call(this);
  33360. };
  33361. ArcRotateCamera.prototype._checkLimits = function () {
  33362. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  33363. if (this.allowUpsideDown && this.beta > Math.PI) {
  33364. this.beta = this.beta - (2 * Math.PI);
  33365. }
  33366. }
  33367. else {
  33368. if (this.beta < this.lowerBetaLimit) {
  33369. this.beta = this.lowerBetaLimit;
  33370. }
  33371. }
  33372. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  33373. if (this.allowUpsideDown && this.beta < -Math.PI) {
  33374. this.beta = this.beta + (2 * Math.PI);
  33375. }
  33376. }
  33377. else {
  33378. if (this.beta > this.upperBetaLimit) {
  33379. this.beta = this.upperBetaLimit;
  33380. }
  33381. }
  33382. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  33383. this.alpha = this.lowerAlphaLimit;
  33384. }
  33385. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  33386. this.alpha = this.upperAlphaLimit;
  33387. }
  33388. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  33389. this.radius = this.lowerRadiusLimit;
  33390. }
  33391. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  33392. this.radius = this.upperRadiusLimit;
  33393. }
  33394. };
  33395. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  33396. var radiusv3 = this.position.subtract(this._getTargetPosition());
  33397. this.radius = radiusv3.length();
  33398. // Alpha
  33399. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  33400. if (radiusv3.z < 0) {
  33401. this.alpha = 2 * Math.PI - this.alpha;
  33402. }
  33403. // Beta
  33404. this.beta = Math.acos(radiusv3.y / this.radius);
  33405. this._checkLimits();
  33406. };
  33407. ArcRotateCamera.prototype.setPosition = function (position) {
  33408. if (this.position.equals(position)) {
  33409. return;
  33410. }
  33411. this.position.copyFrom(position);
  33412. this.rebuildAnglesAndRadius();
  33413. };
  33414. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  33415. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  33416. if (allowSamePosition === void 0) { allowSamePosition = false; }
  33417. if (target.getBoundingInfo) {
  33418. if (toBoundingCenter) {
  33419. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  33420. }
  33421. else {
  33422. this._targetBoundingCenter = null;
  33423. }
  33424. this._targetHost = target;
  33425. this._target = this._getTargetPosition();
  33426. }
  33427. else {
  33428. var newTarget = target;
  33429. var currentTarget = this._getTargetPosition();
  33430. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  33431. return;
  33432. }
  33433. this._target = newTarget;
  33434. this._targetBoundingCenter = null;
  33435. }
  33436. this.rebuildAnglesAndRadius();
  33437. };
  33438. ArcRotateCamera.prototype._getViewMatrix = function () {
  33439. // Compute
  33440. var cosa = Math.cos(this.alpha);
  33441. var sina = Math.sin(this.alpha);
  33442. var cosb = Math.cos(this.beta);
  33443. var sinb = Math.sin(this.beta);
  33444. if (sinb === 0) {
  33445. sinb = 0.0001;
  33446. }
  33447. var target = this._getTargetPosition();
  33448. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  33449. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  33450. if (!this._collider) {
  33451. this._collider = new BABYLON.Collider();
  33452. }
  33453. this._collider.radius = this.collisionRadius;
  33454. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  33455. this._collisionTriggered = true;
  33456. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  33457. }
  33458. else {
  33459. this.position.copyFrom(this._newPosition);
  33460. var up = this.upVector;
  33461. if (this.allowUpsideDown && sinb < 0) {
  33462. up = up.clone();
  33463. up = up.negate();
  33464. }
  33465. if (this.getScene().useRightHandedSystem) {
  33466. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  33467. }
  33468. else {
  33469. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  33470. }
  33471. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  33472. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  33473. }
  33474. this._currentTarget = target;
  33475. return this._viewMatrix;
  33476. };
  33477. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  33478. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  33479. meshes = meshes || this.getScene().meshes;
  33480. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  33481. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  33482. this.radius = distance * this.zoomOnFactor;
  33483. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  33484. };
  33485. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  33486. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  33487. var meshesOrMinMaxVector;
  33488. var distance;
  33489. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  33490. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  33491. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  33492. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  33493. }
  33494. else {
  33495. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  33496. distance = meshesOrMinMaxVectorAndDistance.distance;
  33497. }
  33498. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  33499. if (!doNotUpdateMaxZ) {
  33500. this.maxZ = distance * 2;
  33501. }
  33502. };
  33503. /**
  33504. * @override
  33505. * Override Camera.createRigCamera
  33506. */
  33507. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  33508. var alphaShift;
  33509. switch (this.cameraRigMode) {
  33510. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33511. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33512. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33513. case BABYLON.Camera.RIG_MODE_VR:
  33514. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  33515. break;
  33516. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33517. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  33518. break;
  33519. }
  33520. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  33521. rigCam._cameraRigParams = {};
  33522. return rigCam;
  33523. };
  33524. /**
  33525. * @override
  33526. * Override Camera._updateRigCameras
  33527. */
  33528. ArcRotateCamera.prototype._updateRigCameras = function () {
  33529. var camLeft = this._rigCameras[0];
  33530. var camRight = this._rigCameras[1];
  33531. camLeft.beta = camRight.beta = this.beta;
  33532. camLeft.radius = camRight.radius = this.radius;
  33533. switch (this.cameraRigMode) {
  33534. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33535. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33536. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33537. case BABYLON.Camera.RIG_MODE_VR:
  33538. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  33539. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  33540. break;
  33541. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33542. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  33543. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  33544. break;
  33545. }
  33546. _super.prototype._updateRigCameras.call(this);
  33547. };
  33548. ArcRotateCamera.prototype.dispose = function () {
  33549. this.inputs.clear();
  33550. _super.prototype.dispose.call(this);
  33551. };
  33552. ArcRotateCamera.prototype.getClassName = function () {
  33553. return "ArcRotateCamera";
  33554. };
  33555. return ArcRotateCamera;
  33556. }(BABYLON.TargetCamera));
  33557. __decorate([
  33558. BABYLON.serialize()
  33559. ], ArcRotateCamera.prototype, "alpha", void 0);
  33560. __decorate([
  33561. BABYLON.serialize()
  33562. ], ArcRotateCamera.prototype, "beta", void 0);
  33563. __decorate([
  33564. BABYLON.serialize()
  33565. ], ArcRotateCamera.prototype, "radius", void 0);
  33566. __decorate([
  33567. BABYLON.serializeAsVector3("target")
  33568. ], ArcRotateCamera.prototype, "_target", void 0);
  33569. __decorate([
  33570. BABYLON.serialize()
  33571. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  33572. __decorate([
  33573. BABYLON.serialize()
  33574. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  33575. __decorate([
  33576. BABYLON.serialize()
  33577. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  33578. __decorate([
  33579. BABYLON.serialize()
  33580. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  33581. __decorate([
  33582. BABYLON.serialize()
  33583. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  33584. __decorate([
  33585. BABYLON.serialize()
  33586. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  33587. __decorate([
  33588. BABYLON.serialize()
  33589. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  33590. __decorate([
  33591. BABYLON.serialize()
  33592. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  33593. __decorate([
  33594. BABYLON.serialize()
  33595. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  33596. __decorate([
  33597. BABYLON.serialize()
  33598. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  33599. __decorate([
  33600. BABYLON.serialize()
  33601. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  33602. __decorate([
  33603. BABYLON.serialize()
  33604. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  33605. __decorate([
  33606. BABYLON.serialize()
  33607. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  33608. __decorate([
  33609. BABYLON.serialize()
  33610. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  33611. BABYLON.ArcRotateCamera = ArcRotateCamera;
  33612. })(BABYLON || (BABYLON = {}));
  33613. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  33614. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  33615. var BABYLON;
  33616. (function (BABYLON) {
  33617. var ArcRotateCameraInputsManager = (function (_super) {
  33618. __extends(ArcRotateCameraInputsManager, _super);
  33619. function ArcRotateCameraInputsManager(camera) {
  33620. return _super.call(this, camera) || this;
  33621. }
  33622. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  33623. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  33624. return this;
  33625. };
  33626. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  33627. this.add(new BABYLON.ArcRotateCameraPointersInput());
  33628. return this;
  33629. };
  33630. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  33631. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  33632. return this;
  33633. };
  33634. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  33635. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  33636. return this;
  33637. };
  33638. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  33639. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  33640. return this;
  33641. };
  33642. return ArcRotateCameraInputsManager;
  33643. }(BABYLON.CameraInputsManager));
  33644. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  33645. })(BABYLON || (BABYLON = {}));
  33646. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  33647. var BABYLON;
  33648. (function (BABYLON) {
  33649. var HemisphericLight = (function (_super) {
  33650. __extends(HemisphericLight, _super);
  33651. /**
  33652. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  33653. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  33654. * The HemisphericLight can't cast shadows.
  33655. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33656. */
  33657. function HemisphericLight(name, direction, scene) {
  33658. var _this = _super.call(this, name, scene) || this;
  33659. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  33660. _this.direction = direction || BABYLON.Vector3.Up();
  33661. return _this;
  33662. }
  33663. HemisphericLight.prototype._buildUniformLayout = function () {
  33664. this._uniformBuffer.addUniform("vLightData", 4);
  33665. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33666. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33667. this._uniformBuffer.addUniform("vLightGround", 3);
  33668. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33669. this._uniformBuffer.addUniform("depthValues", 2);
  33670. this._uniformBuffer.create();
  33671. };
  33672. /**
  33673. * Returns the string "HemisphericLight".
  33674. */
  33675. HemisphericLight.prototype.getClassName = function () {
  33676. return "HemisphericLight";
  33677. };
  33678. /**
  33679. * Sets the HemisphericLight direction towards the passed target (Vector3).
  33680. * Returns the updated direction.
  33681. */
  33682. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  33683. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  33684. return this.direction;
  33685. };
  33686. HemisphericLight.prototype.getShadowGenerator = function () {
  33687. return null;
  33688. };
  33689. /**
  33690. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  33691. * Returns the HemisphericLight.
  33692. */
  33693. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  33694. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  33695. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  33696. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  33697. return this;
  33698. };
  33699. HemisphericLight.prototype._getWorldMatrix = function () {
  33700. if (!this._worldMatrix) {
  33701. this._worldMatrix = BABYLON.Matrix.Identity();
  33702. }
  33703. return this._worldMatrix;
  33704. };
  33705. /**
  33706. * Returns the integer 3.
  33707. */
  33708. HemisphericLight.prototype.getTypeID = function () {
  33709. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  33710. };
  33711. return HemisphericLight;
  33712. }(BABYLON.Light));
  33713. __decorate([
  33714. BABYLON.serializeAsColor3()
  33715. ], HemisphericLight.prototype, "groundColor", void 0);
  33716. __decorate([
  33717. BABYLON.serializeAsVector3()
  33718. ], HemisphericLight.prototype, "direction", void 0);
  33719. BABYLON.HemisphericLight = HemisphericLight;
  33720. })(BABYLON || (BABYLON = {}));
  33721. //# sourceMappingURL=babylon.hemisphericLight.js.map
  33722. var BABYLON;
  33723. (function (BABYLON) {
  33724. var ShadowLight = (function (_super) {
  33725. __extends(ShadowLight, _super);
  33726. function ShadowLight() {
  33727. var _this = _super !== null && _super.apply(this, arguments) || this;
  33728. _this._needProjectionMatrixCompute = true;
  33729. return _this;
  33730. }
  33731. Object.defineProperty(ShadowLight.prototype, "direction", {
  33732. get: function () {
  33733. return this._direction;
  33734. },
  33735. set: function (value) {
  33736. this._direction = value;
  33737. },
  33738. enumerable: true,
  33739. configurable: true
  33740. });
  33741. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  33742. get: function () {
  33743. return this._shadowMinZ;
  33744. },
  33745. set: function (value) {
  33746. this._shadowMinZ = value;
  33747. this.forceProjectionMatrixCompute();
  33748. },
  33749. enumerable: true,
  33750. configurable: true
  33751. });
  33752. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  33753. get: function () {
  33754. return this._shadowMaxZ;
  33755. },
  33756. set: function (value) {
  33757. this._shadowMaxZ = value;
  33758. this.forceProjectionMatrixCompute();
  33759. },
  33760. enumerable: true,
  33761. configurable: true
  33762. });
  33763. /**
  33764. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  33765. */
  33766. ShadowLight.prototype.computeTransformedInformation = function () {
  33767. if (this.parent && this.parent.getWorldMatrix) {
  33768. if (!this.transformedPosition) {
  33769. this.transformedPosition = BABYLON.Vector3.Zero();
  33770. }
  33771. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  33772. // In case the direction is present.
  33773. if (this.direction) {
  33774. if (!this.transformedDirection) {
  33775. this.transformedDirection = BABYLON.Vector3.Zero();
  33776. }
  33777. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  33778. }
  33779. return true;
  33780. }
  33781. return false;
  33782. };
  33783. /**
  33784. * Return the depth scale used for the shadow map.
  33785. */
  33786. ShadowLight.prototype.getDepthScale = function () {
  33787. return 50.0;
  33788. };
  33789. /**
  33790. * Returns the light direction (Vector3) for any passed face index.
  33791. */
  33792. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  33793. return this.transformedDirection ? this.transformedDirection : this.direction;
  33794. };
  33795. /**
  33796. * Returns the DirectionalLight absolute position in the World.
  33797. */
  33798. ShadowLight.prototype.getAbsolutePosition = function () {
  33799. return this.transformedPosition ? this.transformedPosition : this.position;
  33800. };
  33801. /**
  33802. * Sets the DirectionalLight direction toward the passed target (Vector3).
  33803. * Returns the updated DirectionalLight direction (Vector3).
  33804. */
  33805. ShadowLight.prototype.setDirectionToTarget = function (target) {
  33806. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  33807. return this.direction;
  33808. };
  33809. /**
  33810. * Returns the light rotation (Vector3).
  33811. */
  33812. ShadowLight.prototype.getRotation = function () {
  33813. this.direction.normalize();
  33814. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  33815. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  33816. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  33817. };
  33818. /**
  33819. * Boolean : false by default.
  33820. */
  33821. ShadowLight.prototype.needCube = function () {
  33822. return false;
  33823. };
  33824. /**
  33825. * Specifies wether or not the projection matrix should be recomputed this frame.
  33826. */
  33827. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  33828. return this._needProjectionMatrixCompute;
  33829. };
  33830. /**
  33831. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  33832. */
  33833. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  33834. this._needProjectionMatrixCompute = true;
  33835. };
  33836. /**
  33837. * Get the world matrix of the sahdow lights.
  33838. */
  33839. ShadowLight.prototype._getWorldMatrix = function () {
  33840. if (!this._worldMatrix) {
  33841. this._worldMatrix = BABYLON.Matrix.Identity();
  33842. }
  33843. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  33844. return this._worldMatrix;
  33845. };
  33846. /**
  33847. * Gets the minZ used for shadow according to both the scene and the light.
  33848. * @param activeCamera
  33849. */
  33850. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  33851. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  33852. };
  33853. /**
  33854. * Gets the maxZ used for shadow according to both the scene and the light.
  33855. * @param activeCamera
  33856. */
  33857. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  33858. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  33859. };
  33860. /**
  33861. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  33862. * Returns the light.
  33863. */
  33864. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33865. if (this.customProjectionMatrixBuilder) {
  33866. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  33867. }
  33868. else {
  33869. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  33870. }
  33871. return this;
  33872. };
  33873. return ShadowLight;
  33874. }(BABYLON.Light));
  33875. __decorate([
  33876. BABYLON.serializeAsVector3()
  33877. ], ShadowLight.prototype, "position", void 0);
  33878. __decorate([
  33879. BABYLON.serializeAsVector3()
  33880. ], ShadowLight.prototype, "direction", null);
  33881. __decorate([
  33882. BABYLON.serialize()
  33883. ], ShadowLight.prototype, "shadowMinZ", null);
  33884. __decorate([
  33885. BABYLON.serialize()
  33886. ], ShadowLight.prototype, "shadowMaxZ", null);
  33887. BABYLON.ShadowLight = ShadowLight;
  33888. })(BABYLON || (BABYLON = {}));
  33889. //# sourceMappingURL=babylon.shadowLight.js.map
  33890. var BABYLON;
  33891. (function (BABYLON) {
  33892. var PointLight = (function (_super) {
  33893. __extends(PointLight, _super);
  33894. /**
  33895. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  33896. * A PointLight emits the light in every direction.
  33897. * It can cast shadows.
  33898. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  33899. * ```javascript
  33900. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  33901. * ```
  33902. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33903. */
  33904. function PointLight(name, position, scene) {
  33905. var _this = _super.call(this, name, scene) || this;
  33906. _this._shadowAngle = Math.PI / 2;
  33907. _this.position = position;
  33908. return _this;
  33909. }
  33910. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  33911. /**
  33912. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33913. * This specifies what angle the shadow will use to be created.
  33914. *
  33915. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33916. */
  33917. get: function () {
  33918. return this._shadowAngle;
  33919. },
  33920. /**
  33921. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33922. * This specifies what angle the shadow will use to be created.
  33923. *
  33924. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33925. */
  33926. set: function (value) {
  33927. this._shadowAngle = value;
  33928. this.forceProjectionMatrixCompute();
  33929. },
  33930. enumerable: true,
  33931. configurable: true
  33932. });
  33933. Object.defineProperty(PointLight.prototype, "direction", {
  33934. get: function () {
  33935. return this._direction;
  33936. },
  33937. /**
  33938. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33939. */
  33940. set: function (value) {
  33941. var previousNeedCube = this.needCube();
  33942. this._direction = value;
  33943. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  33944. this._shadowGenerator.recreateShadowMap();
  33945. }
  33946. },
  33947. enumerable: true,
  33948. configurable: true
  33949. });
  33950. /**
  33951. * Returns the string "PointLight"
  33952. */
  33953. PointLight.prototype.getClassName = function () {
  33954. return "PointLight";
  33955. };
  33956. /**
  33957. * Returns the integer 0.
  33958. */
  33959. PointLight.prototype.getTypeID = function () {
  33960. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  33961. };
  33962. /**
  33963. * Specifies wether or not the shadowmap should be a cube texture.
  33964. */
  33965. PointLight.prototype.needCube = function () {
  33966. return !this.direction;
  33967. };
  33968. /**
  33969. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  33970. */
  33971. PointLight.prototype.getShadowDirection = function (faceIndex) {
  33972. if (this.direction) {
  33973. return _super.prototype.getShadowDirection.call(this, faceIndex);
  33974. }
  33975. else {
  33976. switch (faceIndex) {
  33977. case 0:
  33978. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  33979. case 1:
  33980. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  33981. case 2:
  33982. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  33983. case 3:
  33984. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  33985. case 4:
  33986. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  33987. case 5:
  33988. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  33989. }
  33990. }
  33991. return BABYLON.Vector3.Zero();
  33992. };
  33993. /**
  33994. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  33995. * - fov = PI / 2
  33996. * - aspect ratio : 1.0
  33997. * - z-near and far equal to the active camera minZ and maxZ.
  33998. * Returns the PointLight.
  33999. */
  34000. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34001. var activeCamera = this.getScene().activeCamera;
  34002. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34003. };
  34004. PointLight.prototype._buildUniformLayout = function () {
  34005. this._uniformBuffer.addUniform("vLightData", 4);
  34006. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34007. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34008. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34009. this._uniformBuffer.addUniform("depthValues", 2);
  34010. this._uniformBuffer.create();
  34011. };
  34012. /**
  34013. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  34014. * Returns the PointLight.
  34015. */
  34016. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  34017. if (this.computeTransformedInformation()) {
  34018. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  34019. return this;
  34020. }
  34021. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  34022. return this;
  34023. };
  34024. return PointLight;
  34025. }(BABYLON.ShadowLight));
  34026. __decorate([
  34027. BABYLON.serialize()
  34028. ], PointLight.prototype, "shadowAngle", null);
  34029. BABYLON.PointLight = PointLight;
  34030. })(BABYLON || (BABYLON = {}));
  34031. //# sourceMappingURL=babylon.pointLight.js.map
  34032. /// <reference path="babylon.light.ts" />
  34033. var BABYLON;
  34034. (function (BABYLON) {
  34035. var DirectionalLight = (function (_super) {
  34036. __extends(DirectionalLight, _super);
  34037. /**
  34038. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  34039. * The directional light is emitted from everywhere in the given direction.
  34040. * It can cast shawdows.
  34041. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34042. */
  34043. function DirectionalLight(name, direction, scene) {
  34044. var _this = _super.call(this, name, scene) || this;
  34045. _this._shadowFrustumSize = 0;
  34046. _this._shadowOrthoScale = 0.5;
  34047. _this.autoUpdateExtends = true;
  34048. // Cache
  34049. _this._orthoLeft = Number.MAX_VALUE;
  34050. _this._orthoRight = Number.MIN_VALUE;
  34051. _this._orthoTop = Number.MIN_VALUE;
  34052. _this._orthoBottom = Number.MAX_VALUE;
  34053. _this.position = direction.scale(-1.0);
  34054. _this.direction = direction;
  34055. return _this;
  34056. }
  34057. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  34058. /**
  34059. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  34060. */
  34061. get: function () {
  34062. return this._shadowFrustumSize;
  34063. },
  34064. /**
  34065. * Specifies a fix frustum size for the shadow generation.
  34066. */
  34067. set: function (value) {
  34068. this._shadowFrustumSize = value;
  34069. this.forceProjectionMatrixCompute();
  34070. },
  34071. enumerable: true,
  34072. configurable: true
  34073. });
  34074. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  34075. get: function () {
  34076. return this._shadowOrthoScale;
  34077. },
  34078. set: function (value) {
  34079. this._shadowOrthoScale = value;
  34080. this.forceProjectionMatrixCompute();
  34081. },
  34082. enumerable: true,
  34083. configurable: true
  34084. });
  34085. /**
  34086. * Returns the string "DirectionalLight".
  34087. */
  34088. DirectionalLight.prototype.getClassName = function () {
  34089. return "DirectionalLight";
  34090. };
  34091. /**
  34092. * Returns the integer 1.
  34093. */
  34094. DirectionalLight.prototype.getTypeID = function () {
  34095. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  34096. };
  34097. /**
  34098. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  34099. * Returns the DirectionalLight Shadow projection matrix.
  34100. */
  34101. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34102. if (this.shadowFrustumSize > 0) {
  34103. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  34104. }
  34105. else {
  34106. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  34107. }
  34108. };
  34109. /**
  34110. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  34111. * Returns the DirectionalLight Shadow projection matrix.
  34112. */
  34113. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  34114. var activeCamera = this.getScene().activeCamera;
  34115. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  34116. };
  34117. /**
  34118. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  34119. * Returns the DirectionalLight Shadow projection matrix.
  34120. */
  34121. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34122. var activeCamera = this.getScene().activeCamera;
  34123. // Check extends
  34124. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  34125. var tempVector3 = BABYLON.Vector3.Zero();
  34126. this._orthoLeft = Number.MAX_VALUE;
  34127. this._orthoRight = Number.MIN_VALUE;
  34128. this._orthoTop = Number.MIN_VALUE;
  34129. this._orthoBottom = Number.MAX_VALUE;
  34130. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  34131. var mesh = renderList[meshIndex];
  34132. if (!mesh) {
  34133. continue;
  34134. }
  34135. var boundingInfo = mesh.getBoundingInfo();
  34136. if (!boundingInfo) {
  34137. continue;
  34138. }
  34139. var boundingBox = boundingInfo.boundingBox;
  34140. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  34141. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  34142. if (tempVector3.x < this._orthoLeft)
  34143. this._orthoLeft = tempVector3.x;
  34144. if (tempVector3.y < this._orthoBottom)
  34145. this._orthoBottom = tempVector3.y;
  34146. if (tempVector3.x > this._orthoRight)
  34147. this._orthoRight = tempVector3.x;
  34148. if (tempVector3.y > this._orthoTop)
  34149. this._orthoTop = tempVector3.y;
  34150. }
  34151. }
  34152. }
  34153. var xOffset = this._orthoRight - this._orthoLeft;
  34154. var yOffset = this._orthoTop - this._orthoBottom;
  34155. 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);
  34156. };
  34157. DirectionalLight.prototype._buildUniformLayout = function () {
  34158. this._uniformBuffer.addUniform("vLightData", 4);
  34159. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34160. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34161. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34162. this._uniformBuffer.addUniform("depthValues", 2);
  34163. this._uniformBuffer.create();
  34164. };
  34165. /**
  34166. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  34167. * Returns the DirectionalLight.
  34168. */
  34169. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  34170. if (this.computeTransformedInformation()) {
  34171. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  34172. return this;
  34173. }
  34174. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  34175. return this;
  34176. };
  34177. /**
  34178. * Gets the minZ used for shadow according to both the scene and the light.
  34179. *
  34180. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34181. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34182. * @param activeCamera
  34183. */
  34184. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  34185. return 1;
  34186. };
  34187. /**
  34188. * Gets the maxZ used for shadow according to both the scene and the light.
  34189. *
  34190. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34191. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34192. * @param activeCamera
  34193. */
  34194. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  34195. return 1;
  34196. };
  34197. return DirectionalLight;
  34198. }(BABYLON.ShadowLight));
  34199. __decorate([
  34200. BABYLON.serialize()
  34201. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  34202. __decorate([
  34203. BABYLON.serialize()
  34204. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  34205. __decorate([
  34206. BABYLON.serialize()
  34207. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  34208. BABYLON.DirectionalLight = DirectionalLight;
  34209. })(BABYLON || (BABYLON = {}));
  34210. //# sourceMappingURL=babylon.directionalLight.js.map
  34211. var BABYLON;
  34212. (function (BABYLON) {
  34213. var SpotLight = (function (_super) {
  34214. __extends(SpotLight, _super);
  34215. /**
  34216. * Creates a SpotLight object in the scene with the passed parameters :
  34217. * - `position` (Vector3) is the initial SpotLight position,
  34218. * - `direction` (Vector3) is the initial SpotLight direction,
  34219. * - `angle` (float, in radians) is the spot light cone angle,
  34220. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  34221. * A spot light is a simply light oriented cone.
  34222. * It can cast shadows.
  34223. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34224. */
  34225. function SpotLight(name, position, direction, angle, exponent, scene) {
  34226. var _this = _super.call(this, name, scene) || this;
  34227. _this.position = position;
  34228. _this.direction = direction;
  34229. _this.angle = angle;
  34230. _this.exponent = exponent;
  34231. return _this;
  34232. }
  34233. Object.defineProperty(SpotLight.prototype, "angle", {
  34234. get: function () {
  34235. return this._angle;
  34236. },
  34237. set: function (value) {
  34238. this._angle = value;
  34239. this.forceProjectionMatrixCompute();
  34240. },
  34241. enumerable: true,
  34242. configurable: true
  34243. });
  34244. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  34245. get: function () {
  34246. return this._shadowAngleScale;
  34247. },
  34248. /**
  34249. * Allows scaling the angle of the light for shadow generation only.
  34250. */
  34251. set: function (value) {
  34252. this._shadowAngleScale = value;
  34253. this.forceProjectionMatrixCompute();
  34254. },
  34255. enumerable: true,
  34256. configurable: true
  34257. });
  34258. /**
  34259. * Returns the string "SpotLight".
  34260. */
  34261. SpotLight.prototype.getClassName = function () {
  34262. return "SpotLight";
  34263. };
  34264. /**
  34265. * Returns the integer 2.
  34266. */
  34267. SpotLight.prototype.getTypeID = function () {
  34268. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  34269. };
  34270. /**
  34271. * 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.
  34272. * Returns the SpotLight.
  34273. */
  34274. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34275. var activeCamera = this.getScene().activeCamera;
  34276. this._shadowAngleScale = this._shadowAngleScale || 1;
  34277. var angle = this._shadowAngleScale * this._angle;
  34278. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34279. };
  34280. SpotLight.prototype._buildUniformLayout = function () {
  34281. this._uniformBuffer.addUniform("vLightData", 4);
  34282. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34283. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34284. this._uniformBuffer.addUniform("vLightDirection", 3);
  34285. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34286. this._uniformBuffer.addUniform("depthValues", 2);
  34287. this._uniformBuffer.create();
  34288. };
  34289. /**
  34290. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  34291. * Return the SpotLight.
  34292. */
  34293. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  34294. var normalizeDirection;
  34295. if (this.computeTransformedInformation()) {
  34296. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  34297. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  34298. }
  34299. else {
  34300. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  34301. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  34302. }
  34303. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  34304. return this;
  34305. };
  34306. return SpotLight;
  34307. }(BABYLON.ShadowLight));
  34308. __decorate([
  34309. BABYLON.serialize()
  34310. ], SpotLight.prototype, "angle", null);
  34311. __decorate([
  34312. BABYLON.serialize()
  34313. /**
  34314. * Allows scaling the angle of the light for shadow generation only.
  34315. */
  34316. ], SpotLight.prototype, "shadowAngleScale", null);
  34317. __decorate([
  34318. BABYLON.serialize()
  34319. ], SpotLight.prototype, "exponent", void 0);
  34320. BABYLON.SpotLight = SpotLight;
  34321. })(BABYLON || (BABYLON = {}));
  34322. //# sourceMappingURL=babylon.spotLight.js.map
  34323. var BABYLON;
  34324. (function (BABYLON) {
  34325. var AnimationRange = (function () {
  34326. function AnimationRange(name, from, to) {
  34327. this.name = name;
  34328. this.from = from;
  34329. this.to = to;
  34330. }
  34331. AnimationRange.prototype.clone = function () {
  34332. return new AnimationRange(this.name, this.from, this.to);
  34333. };
  34334. return AnimationRange;
  34335. }());
  34336. BABYLON.AnimationRange = AnimationRange;
  34337. /**
  34338. * Composed of a frame, and an action function
  34339. */
  34340. var AnimationEvent = (function () {
  34341. function AnimationEvent(frame, action, onlyOnce) {
  34342. this.frame = frame;
  34343. this.action = action;
  34344. this.onlyOnce = onlyOnce;
  34345. this.isDone = false;
  34346. }
  34347. return AnimationEvent;
  34348. }());
  34349. BABYLON.AnimationEvent = AnimationEvent;
  34350. var PathCursor = (function () {
  34351. function PathCursor(path) {
  34352. this.path = path;
  34353. this._onchange = new Array();
  34354. this.value = 0;
  34355. this.animations = new Array();
  34356. }
  34357. PathCursor.prototype.getPoint = function () {
  34358. var point = this.path.getPointAtLengthPosition(this.value);
  34359. return new BABYLON.Vector3(point.x, 0, point.y);
  34360. };
  34361. PathCursor.prototype.moveAhead = function (step) {
  34362. if (step === void 0) { step = 0.002; }
  34363. this.move(step);
  34364. return this;
  34365. };
  34366. PathCursor.prototype.moveBack = function (step) {
  34367. if (step === void 0) { step = 0.002; }
  34368. this.move(-step);
  34369. return this;
  34370. };
  34371. PathCursor.prototype.move = function (step) {
  34372. if (Math.abs(step) > 1) {
  34373. throw "step size should be less than 1.";
  34374. }
  34375. this.value += step;
  34376. this.ensureLimits();
  34377. this.raiseOnChange();
  34378. return this;
  34379. };
  34380. PathCursor.prototype.ensureLimits = function () {
  34381. while (this.value > 1) {
  34382. this.value -= 1;
  34383. }
  34384. while (this.value < 0) {
  34385. this.value += 1;
  34386. }
  34387. return this;
  34388. };
  34389. // used by animation engine
  34390. PathCursor.prototype.markAsDirty = function (propertyName) {
  34391. this.ensureLimits();
  34392. this.raiseOnChange();
  34393. return this;
  34394. };
  34395. PathCursor.prototype.raiseOnChange = function () {
  34396. var _this = this;
  34397. this._onchange.forEach(function (f) { return f(_this); });
  34398. return this;
  34399. };
  34400. PathCursor.prototype.onchange = function (f) {
  34401. this._onchange.push(f);
  34402. return this;
  34403. };
  34404. return PathCursor;
  34405. }());
  34406. BABYLON.PathCursor = PathCursor;
  34407. var Animation = (function () {
  34408. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  34409. this.name = name;
  34410. this.targetProperty = targetProperty;
  34411. this.framePerSecond = framePerSecond;
  34412. this.dataType = dataType;
  34413. this.loopMode = loopMode;
  34414. this.enableBlending = enableBlending;
  34415. this._offsetsCache = {};
  34416. this._highLimitsCache = {};
  34417. this._stopped = false;
  34418. this._blendingFactor = 0;
  34419. // The set of event that will be linked to this animation
  34420. this._events = new Array();
  34421. this.allowMatricesInterpolation = false;
  34422. this.blendingSpeed = 0.01;
  34423. this._ranges = {};
  34424. this.targetPropertyPath = targetProperty.split(".");
  34425. this.dataType = dataType;
  34426. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  34427. }
  34428. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  34429. var dataType = undefined;
  34430. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  34431. dataType = Animation.ANIMATIONTYPE_FLOAT;
  34432. }
  34433. else if (from instanceof BABYLON.Quaternion) {
  34434. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  34435. }
  34436. else if (from instanceof BABYLON.Vector3) {
  34437. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  34438. }
  34439. else if (from instanceof BABYLON.Vector2) {
  34440. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  34441. }
  34442. else if (from instanceof BABYLON.Color3) {
  34443. dataType = Animation.ANIMATIONTYPE_COLOR3;
  34444. }
  34445. else if (from instanceof BABYLON.Size) {
  34446. dataType = Animation.ANIMATIONTYPE_SIZE;
  34447. }
  34448. if (dataType == undefined) {
  34449. return null;
  34450. }
  34451. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  34452. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  34453. animation.setKeys(keys);
  34454. if (easingFunction !== undefined) {
  34455. animation.setEasingFunction(easingFunction);
  34456. }
  34457. return animation;
  34458. };
  34459. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  34460. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  34461. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  34462. };
  34463. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  34464. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  34465. node.animations.push(animation);
  34466. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  34467. };
  34468. // Methods
  34469. /**
  34470. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  34471. */
  34472. Animation.prototype.toString = function (fullDetails) {
  34473. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  34474. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  34475. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  34476. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  34477. if (fullDetails) {
  34478. ret += ", Ranges: {";
  34479. var first = true;
  34480. for (var name in this._ranges) {
  34481. if (first) {
  34482. ret += ", ";
  34483. first = false;
  34484. }
  34485. ret += name;
  34486. }
  34487. ret += "}";
  34488. }
  34489. return ret;
  34490. };
  34491. /**
  34492. * Add an event to this animation.
  34493. */
  34494. Animation.prototype.addEvent = function (event) {
  34495. this._events.push(event);
  34496. };
  34497. /**
  34498. * Remove all events found at the given frame
  34499. * @param frame
  34500. */
  34501. Animation.prototype.removeEvents = function (frame) {
  34502. for (var index = 0; index < this._events.length; index++) {
  34503. if (this._events[index].frame === frame) {
  34504. this._events.splice(index, 1);
  34505. index--;
  34506. }
  34507. }
  34508. };
  34509. Animation.prototype.createRange = function (name, from, to) {
  34510. // check name not already in use; could happen for bones after serialized
  34511. if (!this._ranges[name]) {
  34512. this._ranges[name] = new AnimationRange(name, from, to);
  34513. }
  34514. };
  34515. Animation.prototype.deleteRange = function (name, deleteFrames) {
  34516. if (deleteFrames === void 0) { deleteFrames = true; }
  34517. if (this._ranges[name]) {
  34518. if (deleteFrames) {
  34519. var from = this._ranges[name].from;
  34520. var to = this._ranges[name].to;
  34521. // this loop MUST go high to low for multiple splices to work
  34522. for (var key = this._keys.length - 1; key >= 0; key--) {
  34523. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  34524. this._keys.splice(key, 1);
  34525. }
  34526. }
  34527. }
  34528. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  34529. }
  34530. };
  34531. Animation.prototype.getRange = function (name) {
  34532. return this._ranges[name];
  34533. };
  34534. Animation.prototype.reset = function () {
  34535. this._offsetsCache = {};
  34536. this._highLimitsCache = {};
  34537. this.currentFrame = 0;
  34538. this._blendingFactor = 0;
  34539. this._originalBlendValue = null;
  34540. };
  34541. Animation.prototype.isStopped = function () {
  34542. return this._stopped;
  34543. };
  34544. Animation.prototype.getKeys = function () {
  34545. return this._keys;
  34546. };
  34547. Animation.prototype.getHighestFrame = function () {
  34548. var ret = 0;
  34549. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  34550. if (ret < this._keys[key].frame) {
  34551. ret = this._keys[key].frame;
  34552. }
  34553. }
  34554. return ret;
  34555. };
  34556. Animation.prototype.getEasingFunction = function () {
  34557. return this._easingFunction;
  34558. };
  34559. Animation.prototype.setEasingFunction = function (easingFunction) {
  34560. this._easingFunction = easingFunction;
  34561. };
  34562. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  34563. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  34564. };
  34565. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34566. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34567. };
  34568. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  34569. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  34570. };
  34571. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34572. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  34573. };
  34574. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  34575. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  34576. };
  34577. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34578. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34579. };
  34580. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  34581. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  34582. };
  34583. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34584. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34585. };
  34586. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  34587. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  34588. };
  34589. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  34590. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  34591. };
  34592. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  34593. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  34594. };
  34595. Animation.prototype.clone = function () {
  34596. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  34597. clone.enableBlending = this.enableBlending;
  34598. clone.blendingSpeed = this.blendingSpeed;
  34599. if (this._keys) {
  34600. clone.setKeys(this._keys);
  34601. }
  34602. if (this._ranges) {
  34603. clone._ranges = {};
  34604. for (var name in this._ranges) {
  34605. clone._ranges[name] = this._ranges[name].clone();
  34606. }
  34607. }
  34608. return clone;
  34609. };
  34610. Animation.prototype.setKeys = function (values) {
  34611. this._keys = values.slice(0);
  34612. this._offsetsCache = {};
  34613. this._highLimitsCache = {};
  34614. };
  34615. Animation.prototype._getKeyValue = function (value) {
  34616. if (typeof value === "function") {
  34617. return value();
  34618. }
  34619. return value;
  34620. };
  34621. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  34622. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  34623. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  34624. }
  34625. this.currentFrame = currentFrame;
  34626. // Try to get a hash to find the right key
  34627. var startKeyIndex = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  34628. if (this._keys[startKeyIndex].frame >= currentFrame) {
  34629. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  34630. startKeyIndex--;
  34631. }
  34632. }
  34633. for (var key = startKeyIndex; key < this._keys.length; key++) {
  34634. var endKey = this._keys[key + 1];
  34635. if (endKey.frame >= currentFrame) {
  34636. var startKey = this._keys[key];
  34637. var startValue = this._getKeyValue(startKey.value);
  34638. var endValue = this._getKeyValue(endKey.value);
  34639. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  34640. var frameDelta = endKey.frame - startKey.frame;
  34641. // gradient : percent of currentFrame between the frame inf and the frame sup
  34642. var gradient = (currentFrame - startKey.frame) / frameDelta;
  34643. // check for easingFunction and correction of gradient
  34644. if (this._easingFunction != null) {
  34645. gradient = this._easingFunction.ease(gradient);
  34646. }
  34647. switch (this.dataType) {
  34648. // Float
  34649. case Animation.ANIMATIONTYPE_FLOAT:
  34650. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  34651. switch (loopMode) {
  34652. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34653. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34654. return floatValue;
  34655. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34656. return offsetValue * repeatCount + floatValue;
  34657. }
  34658. break;
  34659. // Quaternion
  34660. case Animation.ANIMATIONTYPE_QUATERNION:
  34661. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  34662. switch (loopMode) {
  34663. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34664. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34665. return quatValue;
  34666. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34667. return quatValue.add(offsetValue.scale(repeatCount));
  34668. }
  34669. return quatValue;
  34670. // Vector3
  34671. case Animation.ANIMATIONTYPE_VECTOR3:
  34672. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  34673. switch (loopMode) {
  34674. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34675. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34676. return vec3Value;
  34677. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34678. return vec3Value.add(offsetValue.scale(repeatCount));
  34679. }
  34680. // Vector2
  34681. case Animation.ANIMATIONTYPE_VECTOR2:
  34682. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  34683. switch (loopMode) {
  34684. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34685. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34686. return vec2Value;
  34687. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34688. return vec2Value.add(offsetValue.scale(repeatCount));
  34689. }
  34690. // Size
  34691. case Animation.ANIMATIONTYPE_SIZE:
  34692. switch (loopMode) {
  34693. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34694. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34695. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  34696. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34697. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34698. }
  34699. // Color3
  34700. case Animation.ANIMATIONTYPE_COLOR3:
  34701. switch (loopMode) {
  34702. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34703. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34704. return this.color3InterpolateFunction(startValue, endValue, gradient);
  34705. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34706. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34707. }
  34708. // Matrix
  34709. case Animation.ANIMATIONTYPE_MATRIX:
  34710. switch (loopMode) {
  34711. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34712. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34713. if (this.allowMatricesInterpolation) {
  34714. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  34715. }
  34716. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34717. return startValue;
  34718. }
  34719. default:
  34720. break;
  34721. }
  34722. break;
  34723. }
  34724. }
  34725. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  34726. };
  34727. Animation.prototype.setValue = function (currentValue, blend) {
  34728. if (blend === void 0) { blend = false; }
  34729. // Set value
  34730. var path;
  34731. var destination;
  34732. if (this.targetPropertyPath.length > 1) {
  34733. var property = this._target[this.targetPropertyPath[0]];
  34734. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  34735. property = property[this.targetPropertyPath[index]];
  34736. }
  34737. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  34738. destination = property;
  34739. }
  34740. else {
  34741. path = this.targetPropertyPath[0];
  34742. destination = this._target;
  34743. }
  34744. // Blending
  34745. if (this.enableBlending && this._blendingFactor <= 1.0) {
  34746. if (!this._originalBlendValue) {
  34747. if (destination[path].clone) {
  34748. this._originalBlendValue = destination[path].clone();
  34749. }
  34750. else {
  34751. this._originalBlendValue = destination[path];
  34752. }
  34753. }
  34754. if (this._originalBlendValue.prototype) {
  34755. if (this._originalBlendValue.prototype.Lerp) {
  34756. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  34757. }
  34758. else {
  34759. destination[path] = currentValue;
  34760. }
  34761. }
  34762. else if (this._originalBlendValue.m) {
  34763. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  34764. }
  34765. else {
  34766. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  34767. }
  34768. this._blendingFactor += this.blendingSpeed;
  34769. }
  34770. else {
  34771. destination[path] = currentValue;
  34772. }
  34773. if (this._target.markAsDirty) {
  34774. this._target.markAsDirty(this.targetProperty);
  34775. }
  34776. };
  34777. Animation.prototype.goToFrame = function (frame) {
  34778. if (frame < this._keys[0].frame) {
  34779. frame = this._keys[0].frame;
  34780. }
  34781. else if (frame > this._keys[this._keys.length - 1].frame) {
  34782. frame = this._keys[this._keys.length - 1].frame;
  34783. }
  34784. var currentValue = this._interpolate(frame, 0, this.loopMode);
  34785. this.setValue(currentValue);
  34786. };
  34787. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  34788. if (blend === void 0) { blend = false; }
  34789. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  34790. this._stopped = true;
  34791. return false;
  34792. }
  34793. var returnValue = true;
  34794. // Adding a start key at frame 0 if missing
  34795. if (this._keys[0].frame !== 0) {
  34796. var newKey = { frame: 0, value: this._keys[0].value };
  34797. this._keys.splice(0, 0, newKey);
  34798. }
  34799. // Check limits
  34800. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  34801. from = this._keys[0].frame;
  34802. }
  34803. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  34804. to = this._keys[this._keys.length - 1].frame;
  34805. }
  34806. //to and from cannot be the same key
  34807. if (from === to) {
  34808. from++;
  34809. }
  34810. // Compute ratio
  34811. var range = to - from;
  34812. var offsetValue;
  34813. // ratio represents the frame delta between from and to
  34814. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  34815. var highLimitValue = 0;
  34816. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  34817. returnValue = false;
  34818. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  34819. }
  34820. else {
  34821. // Get max value if required
  34822. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  34823. var keyOffset = to.toString() + from.toString();
  34824. if (!this._offsetsCache[keyOffset]) {
  34825. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34826. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34827. switch (this.dataType) {
  34828. // Float
  34829. case Animation.ANIMATIONTYPE_FLOAT:
  34830. this._offsetsCache[keyOffset] = toValue - fromValue;
  34831. break;
  34832. // Quaternion
  34833. case Animation.ANIMATIONTYPE_QUATERNION:
  34834. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34835. break;
  34836. // Vector3
  34837. case Animation.ANIMATIONTYPE_VECTOR3:
  34838. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34839. // Vector2
  34840. case Animation.ANIMATIONTYPE_VECTOR2:
  34841. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34842. // Size
  34843. case Animation.ANIMATIONTYPE_SIZE:
  34844. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34845. // Color3
  34846. case Animation.ANIMATIONTYPE_COLOR3:
  34847. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34848. default:
  34849. break;
  34850. }
  34851. this._highLimitsCache[keyOffset] = toValue;
  34852. }
  34853. highLimitValue = this._highLimitsCache[keyOffset];
  34854. offsetValue = this._offsetsCache[keyOffset];
  34855. }
  34856. }
  34857. if (offsetValue === undefined) {
  34858. switch (this.dataType) {
  34859. // Float
  34860. case Animation.ANIMATIONTYPE_FLOAT:
  34861. offsetValue = 0;
  34862. break;
  34863. // Quaternion
  34864. case Animation.ANIMATIONTYPE_QUATERNION:
  34865. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  34866. break;
  34867. // Vector3
  34868. case Animation.ANIMATIONTYPE_VECTOR3:
  34869. offsetValue = BABYLON.Vector3.Zero();
  34870. break;
  34871. // Vector2
  34872. case Animation.ANIMATIONTYPE_VECTOR2:
  34873. offsetValue = BABYLON.Vector2.Zero();
  34874. break;
  34875. // Size
  34876. case Animation.ANIMATIONTYPE_SIZE:
  34877. offsetValue = BABYLON.Size.Zero();
  34878. break;
  34879. // Color3
  34880. case Animation.ANIMATIONTYPE_COLOR3:
  34881. offsetValue = BABYLON.Color3.Black();
  34882. }
  34883. }
  34884. // Compute value
  34885. var repeatCount = (ratio / range) >> 0;
  34886. var currentFrame = returnValue ? from + ratio % range : to;
  34887. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  34888. // Set value
  34889. this.setValue(currentValue);
  34890. // Check events
  34891. for (var index = 0; index < this._events.length; index++) {
  34892. if (currentFrame >= this._events[index].frame) {
  34893. var event = this._events[index];
  34894. if (!event.isDone) {
  34895. // If event should be done only once, remove it.
  34896. if (event.onlyOnce) {
  34897. this._events.splice(index, 1);
  34898. index--;
  34899. }
  34900. event.isDone = true;
  34901. event.action();
  34902. } // Don't do anything if the event has already be done.
  34903. }
  34904. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  34905. // reset event, the animation is looping
  34906. this._events[index].isDone = false;
  34907. }
  34908. }
  34909. if (!returnValue) {
  34910. this._stopped = true;
  34911. }
  34912. return returnValue;
  34913. };
  34914. Animation.prototype.serialize = function () {
  34915. var serializationObject = {};
  34916. serializationObject.name = this.name;
  34917. serializationObject.property = this.targetProperty;
  34918. serializationObject.framePerSecond = this.framePerSecond;
  34919. serializationObject.dataType = this.dataType;
  34920. serializationObject.loopBehavior = this.loopMode;
  34921. serializationObject.enableBlending = this.enableBlending;
  34922. serializationObject.blendingSpeed = this.blendingSpeed;
  34923. var dataType = this.dataType;
  34924. serializationObject.keys = [];
  34925. var keys = this.getKeys();
  34926. for (var index = 0; index < keys.length; index++) {
  34927. var animationKey = keys[index];
  34928. var key = {};
  34929. key.frame = animationKey.frame;
  34930. switch (dataType) {
  34931. case Animation.ANIMATIONTYPE_FLOAT:
  34932. key.values = [animationKey.value];
  34933. break;
  34934. case Animation.ANIMATIONTYPE_QUATERNION:
  34935. case Animation.ANIMATIONTYPE_MATRIX:
  34936. case Animation.ANIMATIONTYPE_VECTOR3:
  34937. case Animation.ANIMATIONTYPE_COLOR3:
  34938. key.values = animationKey.value.asArray();
  34939. break;
  34940. }
  34941. serializationObject.keys.push(key);
  34942. }
  34943. serializationObject.ranges = [];
  34944. for (var name in this._ranges) {
  34945. var range = {};
  34946. range.name = name;
  34947. range.from = this._ranges[name].from;
  34948. range.to = this._ranges[name].to;
  34949. serializationObject.ranges.push(range);
  34950. }
  34951. return serializationObject;
  34952. };
  34953. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  34954. get: function () {
  34955. return Animation._ANIMATIONTYPE_FLOAT;
  34956. },
  34957. enumerable: true,
  34958. configurable: true
  34959. });
  34960. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  34961. get: function () {
  34962. return Animation._ANIMATIONTYPE_VECTOR3;
  34963. },
  34964. enumerable: true,
  34965. configurable: true
  34966. });
  34967. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  34968. get: function () {
  34969. return Animation._ANIMATIONTYPE_VECTOR2;
  34970. },
  34971. enumerable: true,
  34972. configurable: true
  34973. });
  34974. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  34975. get: function () {
  34976. return Animation._ANIMATIONTYPE_SIZE;
  34977. },
  34978. enumerable: true,
  34979. configurable: true
  34980. });
  34981. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  34982. get: function () {
  34983. return Animation._ANIMATIONTYPE_QUATERNION;
  34984. },
  34985. enumerable: true,
  34986. configurable: true
  34987. });
  34988. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  34989. get: function () {
  34990. return Animation._ANIMATIONTYPE_MATRIX;
  34991. },
  34992. enumerable: true,
  34993. configurable: true
  34994. });
  34995. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  34996. get: function () {
  34997. return Animation._ANIMATIONTYPE_COLOR3;
  34998. },
  34999. enumerable: true,
  35000. configurable: true
  35001. });
  35002. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  35003. get: function () {
  35004. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  35005. },
  35006. enumerable: true,
  35007. configurable: true
  35008. });
  35009. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  35010. get: function () {
  35011. return Animation._ANIMATIONLOOPMODE_CYCLE;
  35012. },
  35013. enumerable: true,
  35014. configurable: true
  35015. });
  35016. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  35017. get: function () {
  35018. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  35019. },
  35020. enumerable: true,
  35021. configurable: true
  35022. });
  35023. Animation.Parse = function (parsedAnimation) {
  35024. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  35025. var dataType = parsedAnimation.dataType;
  35026. var keys = [];
  35027. var data;
  35028. var index;
  35029. if (parsedAnimation.enableBlending) {
  35030. animation.enableBlending = parsedAnimation.enableBlending;
  35031. }
  35032. if (parsedAnimation.blendingSpeed) {
  35033. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  35034. }
  35035. for (index = 0; index < parsedAnimation.keys.length; index++) {
  35036. var key = parsedAnimation.keys[index];
  35037. switch (dataType) {
  35038. case Animation.ANIMATIONTYPE_FLOAT:
  35039. data = key.values[0];
  35040. break;
  35041. case Animation.ANIMATIONTYPE_QUATERNION:
  35042. data = BABYLON.Quaternion.FromArray(key.values);
  35043. break;
  35044. case Animation.ANIMATIONTYPE_MATRIX:
  35045. data = BABYLON.Matrix.FromArray(key.values);
  35046. break;
  35047. case Animation.ANIMATIONTYPE_COLOR3:
  35048. data = BABYLON.Color3.FromArray(key.values);
  35049. break;
  35050. case Animation.ANIMATIONTYPE_VECTOR3:
  35051. default:
  35052. data = BABYLON.Vector3.FromArray(key.values);
  35053. break;
  35054. }
  35055. keys.push({
  35056. frame: key.frame,
  35057. value: data
  35058. });
  35059. }
  35060. animation.setKeys(keys);
  35061. if (parsedAnimation.ranges) {
  35062. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  35063. data = parsedAnimation.ranges[index];
  35064. animation.createRange(data.name, data.from, data.to);
  35065. }
  35066. }
  35067. return animation;
  35068. };
  35069. Animation.AppendSerializedAnimations = function (source, destination) {
  35070. if (source.animations) {
  35071. destination.animations = [];
  35072. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  35073. var animation = source.animations[animationIndex];
  35074. destination.animations.push(animation.serialize());
  35075. }
  35076. }
  35077. };
  35078. return Animation;
  35079. }());
  35080. // Statics
  35081. Animation._ANIMATIONTYPE_FLOAT = 0;
  35082. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  35083. Animation._ANIMATIONTYPE_QUATERNION = 2;
  35084. Animation._ANIMATIONTYPE_MATRIX = 3;
  35085. Animation._ANIMATIONTYPE_COLOR3 = 4;
  35086. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  35087. Animation._ANIMATIONTYPE_SIZE = 6;
  35088. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  35089. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  35090. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  35091. BABYLON.Animation = Animation;
  35092. })(BABYLON || (BABYLON = {}));
  35093. //# sourceMappingURL=babylon.animation.js.map
  35094. var BABYLON;
  35095. (function (BABYLON) {
  35096. var Animatable = (function () {
  35097. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  35098. if (fromFrame === void 0) { fromFrame = 0; }
  35099. if (toFrame === void 0) { toFrame = 100; }
  35100. if (loopAnimation === void 0) { loopAnimation = false; }
  35101. if (speedRatio === void 0) { speedRatio = 1.0; }
  35102. this.target = target;
  35103. this.fromFrame = fromFrame;
  35104. this.toFrame = toFrame;
  35105. this.loopAnimation = loopAnimation;
  35106. this.speedRatio = speedRatio;
  35107. this.onAnimationEnd = onAnimationEnd;
  35108. this._localDelayOffset = null;
  35109. this._pausedDelay = null;
  35110. this._animations = new Array();
  35111. this._paused = false;
  35112. this.animationStarted = false;
  35113. if (animations) {
  35114. this.appendAnimations(target, animations);
  35115. }
  35116. this._scene = scene;
  35117. scene._activeAnimatables.push(this);
  35118. }
  35119. // Methods
  35120. Animatable.prototype.getAnimations = function () {
  35121. return this._animations;
  35122. };
  35123. Animatable.prototype.appendAnimations = function (target, animations) {
  35124. for (var index = 0; index < animations.length; index++) {
  35125. var animation = animations[index];
  35126. animation._target = target;
  35127. this._animations.push(animation);
  35128. }
  35129. };
  35130. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  35131. var animations = this._animations;
  35132. for (var index = 0; index < animations.length; index++) {
  35133. if (animations[index].targetProperty === property) {
  35134. return animations[index];
  35135. }
  35136. }
  35137. return null;
  35138. };
  35139. Animatable.prototype.reset = function () {
  35140. var animations = this._animations;
  35141. for (var index = 0; index < animations.length; index++) {
  35142. animations[index].reset();
  35143. }
  35144. this._localDelayOffset = null;
  35145. this._pausedDelay = null;
  35146. };
  35147. Animatable.prototype.enableBlending = function (blendingSpeed) {
  35148. var animations = this._animations;
  35149. for (var index = 0; index < animations.length; index++) {
  35150. animations[index].enableBlending = true;
  35151. animations[index].blendingSpeed = blendingSpeed;
  35152. }
  35153. };
  35154. Animatable.prototype.disableBlending = function () {
  35155. var animations = this._animations;
  35156. for (var index = 0; index < animations.length; index++) {
  35157. animations[index].enableBlending = false;
  35158. }
  35159. };
  35160. Animatable.prototype.goToFrame = function (frame) {
  35161. var animations = this._animations;
  35162. if (animations[0]) {
  35163. var fps = animations[0].framePerSecond;
  35164. var currentFrame = animations[0].currentFrame;
  35165. var adjustTime = frame - currentFrame;
  35166. var delay = adjustTime * 1000 / fps;
  35167. this._localDelayOffset -= delay;
  35168. }
  35169. for (var index = 0; index < animations.length; index++) {
  35170. animations[index].goToFrame(frame);
  35171. }
  35172. };
  35173. Animatable.prototype.pause = function () {
  35174. if (this._paused) {
  35175. return;
  35176. }
  35177. this._paused = true;
  35178. };
  35179. Animatable.prototype.restart = function () {
  35180. this._paused = false;
  35181. };
  35182. Animatable.prototype.stop = function (animationName) {
  35183. if (animationName) {
  35184. var idx = this._scene._activeAnimatables.indexOf(this);
  35185. if (idx > -1) {
  35186. var animations = this._animations;
  35187. for (var index = animations.length - 1; index >= 0; index--) {
  35188. if (typeof animationName === "string" && animations[index].name != animationName) {
  35189. continue;
  35190. }
  35191. animations[index].reset();
  35192. animations.splice(index, 1);
  35193. }
  35194. if (animations.length == 0) {
  35195. this._scene._activeAnimatables.splice(idx, 1);
  35196. if (this.onAnimationEnd) {
  35197. this.onAnimationEnd();
  35198. }
  35199. }
  35200. }
  35201. }
  35202. else {
  35203. var index = this._scene._activeAnimatables.indexOf(this);
  35204. if (index > -1) {
  35205. this._scene._activeAnimatables.splice(index, 1);
  35206. var animations = this._animations;
  35207. for (var index = 0; index < animations.length; index++) {
  35208. animations[index].reset();
  35209. }
  35210. if (this.onAnimationEnd) {
  35211. this.onAnimationEnd();
  35212. }
  35213. }
  35214. }
  35215. };
  35216. Animatable.prototype._animate = function (delay) {
  35217. if (this._paused) {
  35218. this.animationStarted = false;
  35219. if (this._pausedDelay === null) {
  35220. this._pausedDelay = delay;
  35221. }
  35222. return true;
  35223. }
  35224. if (this._localDelayOffset === null) {
  35225. this._localDelayOffset = delay;
  35226. }
  35227. else if (this._pausedDelay !== null) {
  35228. this._localDelayOffset += delay - this._pausedDelay;
  35229. this._pausedDelay = null;
  35230. }
  35231. // Animating
  35232. var running = false;
  35233. var animations = this._animations;
  35234. var index;
  35235. for (index = 0; index < animations.length; index++) {
  35236. var animation = animations[index];
  35237. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  35238. running = running || isRunning;
  35239. }
  35240. this.animationStarted = running;
  35241. if (!running) {
  35242. // Remove from active animatables
  35243. index = this._scene._activeAnimatables.indexOf(this);
  35244. this._scene._activeAnimatables.splice(index, 1);
  35245. }
  35246. if (!running && this.onAnimationEnd) {
  35247. this.onAnimationEnd();
  35248. this.onAnimationEnd = null;
  35249. }
  35250. return running;
  35251. };
  35252. return Animatable;
  35253. }());
  35254. BABYLON.Animatable = Animatable;
  35255. })(BABYLON || (BABYLON = {}));
  35256. //# sourceMappingURL=babylon.animatable.js.map
  35257. var BABYLON;
  35258. (function (BABYLON) {
  35259. var EasingFunction = (function () {
  35260. function EasingFunction() {
  35261. // Properties
  35262. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  35263. }
  35264. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  35265. get: function () {
  35266. return EasingFunction._EASINGMODE_EASEIN;
  35267. },
  35268. enumerable: true,
  35269. configurable: true
  35270. });
  35271. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  35272. get: function () {
  35273. return EasingFunction._EASINGMODE_EASEOUT;
  35274. },
  35275. enumerable: true,
  35276. configurable: true
  35277. });
  35278. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  35279. get: function () {
  35280. return EasingFunction._EASINGMODE_EASEINOUT;
  35281. },
  35282. enumerable: true,
  35283. configurable: true
  35284. });
  35285. EasingFunction.prototype.setEasingMode = function (easingMode) {
  35286. var n = Math.min(Math.max(easingMode, 0), 2);
  35287. this._easingMode = n;
  35288. };
  35289. EasingFunction.prototype.getEasingMode = function () {
  35290. return this._easingMode;
  35291. };
  35292. EasingFunction.prototype.easeInCore = function (gradient) {
  35293. throw new Error('You must implement this method');
  35294. };
  35295. EasingFunction.prototype.ease = function (gradient) {
  35296. switch (this._easingMode) {
  35297. case EasingFunction.EASINGMODE_EASEIN:
  35298. return this.easeInCore(gradient);
  35299. case EasingFunction.EASINGMODE_EASEOUT:
  35300. return (1 - this.easeInCore(1 - gradient));
  35301. }
  35302. if (gradient >= 0.5) {
  35303. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  35304. }
  35305. return (this.easeInCore(gradient * 2) * 0.5);
  35306. };
  35307. return EasingFunction;
  35308. }());
  35309. //Statics
  35310. EasingFunction._EASINGMODE_EASEIN = 0;
  35311. EasingFunction._EASINGMODE_EASEOUT = 1;
  35312. EasingFunction._EASINGMODE_EASEINOUT = 2;
  35313. BABYLON.EasingFunction = EasingFunction;
  35314. var CircleEase = (function (_super) {
  35315. __extends(CircleEase, _super);
  35316. function CircleEase() {
  35317. return _super !== null && _super.apply(this, arguments) || this;
  35318. }
  35319. CircleEase.prototype.easeInCore = function (gradient) {
  35320. gradient = Math.max(0, Math.min(1, gradient));
  35321. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  35322. };
  35323. return CircleEase;
  35324. }(EasingFunction));
  35325. BABYLON.CircleEase = CircleEase;
  35326. var BackEase = (function (_super) {
  35327. __extends(BackEase, _super);
  35328. function BackEase(amplitude) {
  35329. if (amplitude === void 0) { amplitude = 1; }
  35330. var _this = _super.call(this) || this;
  35331. _this.amplitude = amplitude;
  35332. return _this;
  35333. }
  35334. BackEase.prototype.easeInCore = function (gradient) {
  35335. var num = Math.max(0, this.amplitude);
  35336. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  35337. };
  35338. return BackEase;
  35339. }(EasingFunction));
  35340. BABYLON.BackEase = BackEase;
  35341. var BounceEase = (function (_super) {
  35342. __extends(BounceEase, _super);
  35343. function BounceEase(bounces, bounciness) {
  35344. if (bounces === void 0) { bounces = 3; }
  35345. if (bounciness === void 0) { bounciness = 2; }
  35346. var _this = _super.call(this) || this;
  35347. _this.bounces = bounces;
  35348. _this.bounciness = bounciness;
  35349. return _this;
  35350. }
  35351. BounceEase.prototype.easeInCore = function (gradient) {
  35352. var y = Math.max(0.0, this.bounces);
  35353. var bounciness = this.bounciness;
  35354. if (bounciness <= 1.0) {
  35355. bounciness = 1.001;
  35356. }
  35357. var num9 = Math.pow(bounciness, y);
  35358. var num5 = 1.0 - bounciness;
  35359. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  35360. var num15 = gradient * num4;
  35361. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  35362. var num3 = Math.floor(num65);
  35363. var num13 = num3 + 1.0;
  35364. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  35365. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  35366. var num7 = (num8 + num12) * 0.5;
  35367. var num6 = gradient - num7;
  35368. var num2 = num7 - num8;
  35369. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  35370. };
  35371. return BounceEase;
  35372. }(EasingFunction));
  35373. BABYLON.BounceEase = BounceEase;
  35374. var CubicEase = (function (_super) {
  35375. __extends(CubicEase, _super);
  35376. function CubicEase() {
  35377. return _super !== null && _super.apply(this, arguments) || this;
  35378. }
  35379. CubicEase.prototype.easeInCore = function (gradient) {
  35380. return (gradient * gradient * gradient);
  35381. };
  35382. return CubicEase;
  35383. }(EasingFunction));
  35384. BABYLON.CubicEase = CubicEase;
  35385. var ElasticEase = (function (_super) {
  35386. __extends(ElasticEase, _super);
  35387. function ElasticEase(oscillations, springiness) {
  35388. if (oscillations === void 0) { oscillations = 3; }
  35389. if (springiness === void 0) { springiness = 3; }
  35390. var _this = _super.call(this) || this;
  35391. _this.oscillations = oscillations;
  35392. _this.springiness = springiness;
  35393. return _this;
  35394. }
  35395. ElasticEase.prototype.easeInCore = function (gradient) {
  35396. var num2;
  35397. var num3 = Math.max(0.0, this.oscillations);
  35398. var num = Math.max(0.0, this.springiness);
  35399. if (num == 0) {
  35400. num2 = gradient;
  35401. }
  35402. else {
  35403. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  35404. }
  35405. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  35406. };
  35407. return ElasticEase;
  35408. }(EasingFunction));
  35409. BABYLON.ElasticEase = ElasticEase;
  35410. var ExponentialEase = (function (_super) {
  35411. __extends(ExponentialEase, _super);
  35412. function ExponentialEase(exponent) {
  35413. if (exponent === void 0) { exponent = 2; }
  35414. var _this = _super.call(this) || this;
  35415. _this.exponent = exponent;
  35416. return _this;
  35417. }
  35418. ExponentialEase.prototype.easeInCore = function (gradient) {
  35419. if (this.exponent <= 0) {
  35420. return gradient;
  35421. }
  35422. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  35423. };
  35424. return ExponentialEase;
  35425. }(EasingFunction));
  35426. BABYLON.ExponentialEase = ExponentialEase;
  35427. var PowerEase = (function (_super) {
  35428. __extends(PowerEase, _super);
  35429. function PowerEase(power) {
  35430. if (power === void 0) { power = 2; }
  35431. var _this = _super.call(this) || this;
  35432. _this.power = power;
  35433. return _this;
  35434. }
  35435. PowerEase.prototype.easeInCore = function (gradient) {
  35436. var y = Math.max(0.0, this.power);
  35437. return Math.pow(gradient, y);
  35438. };
  35439. return PowerEase;
  35440. }(EasingFunction));
  35441. BABYLON.PowerEase = PowerEase;
  35442. var QuadraticEase = (function (_super) {
  35443. __extends(QuadraticEase, _super);
  35444. function QuadraticEase() {
  35445. return _super !== null && _super.apply(this, arguments) || this;
  35446. }
  35447. QuadraticEase.prototype.easeInCore = function (gradient) {
  35448. return (gradient * gradient);
  35449. };
  35450. return QuadraticEase;
  35451. }(EasingFunction));
  35452. BABYLON.QuadraticEase = QuadraticEase;
  35453. var QuarticEase = (function (_super) {
  35454. __extends(QuarticEase, _super);
  35455. function QuarticEase() {
  35456. return _super !== null && _super.apply(this, arguments) || this;
  35457. }
  35458. QuarticEase.prototype.easeInCore = function (gradient) {
  35459. return (gradient * gradient * gradient * gradient);
  35460. };
  35461. return QuarticEase;
  35462. }(EasingFunction));
  35463. BABYLON.QuarticEase = QuarticEase;
  35464. var QuinticEase = (function (_super) {
  35465. __extends(QuinticEase, _super);
  35466. function QuinticEase() {
  35467. return _super !== null && _super.apply(this, arguments) || this;
  35468. }
  35469. QuinticEase.prototype.easeInCore = function (gradient) {
  35470. return (gradient * gradient * gradient * gradient * gradient);
  35471. };
  35472. return QuinticEase;
  35473. }(EasingFunction));
  35474. BABYLON.QuinticEase = QuinticEase;
  35475. var SineEase = (function (_super) {
  35476. __extends(SineEase, _super);
  35477. function SineEase() {
  35478. return _super !== null && _super.apply(this, arguments) || this;
  35479. }
  35480. SineEase.prototype.easeInCore = function (gradient) {
  35481. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  35482. };
  35483. return SineEase;
  35484. }(EasingFunction));
  35485. BABYLON.SineEase = SineEase;
  35486. var BezierCurveEase = (function (_super) {
  35487. __extends(BezierCurveEase, _super);
  35488. function BezierCurveEase(x1, y1, x2, y2) {
  35489. if (x1 === void 0) { x1 = 0; }
  35490. if (y1 === void 0) { y1 = 0; }
  35491. if (x2 === void 0) { x2 = 1; }
  35492. if (y2 === void 0) { y2 = 1; }
  35493. var _this = _super.call(this) || this;
  35494. _this.x1 = x1;
  35495. _this.y1 = y1;
  35496. _this.x2 = x2;
  35497. _this.y2 = y2;
  35498. return _this;
  35499. }
  35500. BezierCurveEase.prototype.easeInCore = function (gradient) {
  35501. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  35502. };
  35503. return BezierCurveEase;
  35504. }(EasingFunction));
  35505. BABYLON.BezierCurveEase = BezierCurveEase;
  35506. })(BABYLON || (BABYLON = {}));
  35507. //# sourceMappingURL=babylon.easing.js.map
  35508. var BABYLON;
  35509. (function (BABYLON) {
  35510. var Condition = (function () {
  35511. function Condition(actionManager) {
  35512. this._actionManager = actionManager;
  35513. }
  35514. Condition.prototype.isValid = function () {
  35515. return true;
  35516. };
  35517. Condition.prototype._getProperty = function (propertyPath) {
  35518. return this._actionManager._getProperty(propertyPath);
  35519. };
  35520. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  35521. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35522. };
  35523. Condition.prototype.serialize = function () {
  35524. };
  35525. Condition.prototype._serialize = function (serializedCondition) {
  35526. return {
  35527. type: 2,
  35528. children: [],
  35529. name: serializedCondition.name,
  35530. properties: serializedCondition.properties
  35531. };
  35532. };
  35533. return Condition;
  35534. }());
  35535. BABYLON.Condition = Condition;
  35536. var ValueCondition = (function (_super) {
  35537. __extends(ValueCondition, _super);
  35538. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  35539. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  35540. var _this = _super.call(this, actionManager) || this;
  35541. _this.propertyPath = propertyPath;
  35542. _this.value = value;
  35543. _this.operator = operator;
  35544. _this._target = target;
  35545. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  35546. _this._property = _this._getProperty(_this.propertyPath);
  35547. return _this;
  35548. }
  35549. Object.defineProperty(ValueCondition, "IsEqual", {
  35550. get: function () {
  35551. return ValueCondition._IsEqual;
  35552. },
  35553. enumerable: true,
  35554. configurable: true
  35555. });
  35556. Object.defineProperty(ValueCondition, "IsDifferent", {
  35557. get: function () {
  35558. return ValueCondition._IsDifferent;
  35559. },
  35560. enumerable: true,
  35561. configurable: true
  35562. });
  35563. Object.defineProperty(ValueCondition, "IsGreater", {
  35564. get: function () {
  35565. return ValueCondition._IsGreater;
  35566. },
  35567. enumerable: true,
  35568. configurable: true
  35569. });
  35570. Object.defineProperty(ValueCondition, "IsLesser", {
  35571. get: function () {
  35572. return ValueCondition._IsLesser;
  35573. },
  35574. enumerable: true,
  35575. configurable: true
  35576. });
  35577. // Methods
  35578. ValueCondition.prototype.isValid = function () {
  35579. switch (this.operator) {
  35580. case ValueCondition.IsGreater:
  35581. return this._effectiveTarget[this._property] > this.value;
  35582. case ValueCondition.IsLesser:
  35583. return this._effectiveTarget[this._property] < this.value;
  35584. case ValueCondition.IsEqual:
  35585. case ValueCondition.IsDifferent:
  35586. var check;
  35587. if (this.value.equals) {
  35588. check = this.value.equals(this._effectiveTarget[this._property]);
  35589. }
  35590. else {
  35591. check = this.value === this._effectiveTarget[this._property];
  35592. }
  35593. return this.operator === ValueCondition.IsEqual ? check : !check;
  35594. }
  35595. return false;
  35596. };
  35597. ValueCondition.prototype.serialize = function () {
  35598. return this._serialize({
  35599. name: "ValueCondition",
  35600. properties: [
  35601. BABYLON.Action._GetTargetProperty(this._target),
  35602. { name: "propertyPath", value: this.propertyPath },
  35603. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35604. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  35605. ]
  35606. });
  35607. };
  35608. ValueCondition.GetOperatorName = function (operator) {
  35609. switch (operator) {
  35610. case ValueCondition._IsEqual: return "IsEqual";
  35611. case ValueCondition._IsDifferent: return "IsDifferent";
  35612. case ValueCondition._IsGreater: return "IsGreater";
  35613. case ValueCondition._IsLesser: return "IsLesser";
  35614. default: return "";
  35615. }
  35616. };
  35617. return ValueCondition;
  35618. }(Condition));
  35619. // Statics
  35620. ValueCondition._IsEqual = 0;
  35621. ValueCondition._IsDifferent = 1;
  35622. ValueCondition._IsGreater = 2;
  35623. ValueCondition._IsLesser = 3;
  35624. BABYLON.ValueCondition = ValueCondition;
  35625. var PredicateCondition = (function (_super) {
  35626. __extends(PredicateCondition, _super);
  35627. function PredicateCondition(actionManager, predicate) {
  35628. var _this = _super.call(this, actionManager) || this;
  35629. _this.predicate = predicate;
  35630. return _this;
  35631. }
  35632. PredicateCondition.prototype.isValid = function () {
  35633. return this.predicate();
  35634. };
  35635. return PredicateCondition;
  35636. }(Condition));
  35637. BABYLON.PredicateCondition = PredicateCondition;
  35638. var StateCondition = (function (_super) {
  35639. __extends(StateCondition, _super);
  35640. function StateCondition(actionManager, target, value) {
  35641. var _this = _super.call(this, actionManager) || this;
  35642. _this.value = value;
  35643. _this._target = target;
  35644. return _this;
  35645. }
  35646. // Methods
  35647. StateCondition.prototype.isValid = function () {
  35648. return this._target.state === this.value;
  35649. };
  35650. StateCondition.prototype.serialize = function () {
  35651. return this._serialize({
  35652. name: "StateCondition",
  35653. properties: [
  35654. BABYLON.Action._GetTargetProperty(this._target),
  35655. { name: "value", value: this.value }
  35656. ]
  35657. });
  35658. };
  35659. return StateCondition;
  35660. }(Condition));
  35661. BABYLON.StateCondition = StateCondition;
  35662. })(BABYLON || (BABYLON = {}));
  35663. //# sourceMappingURL=babylon.condition.js.map
  35664. var BABYLON;
  35665. (function (BABYLON) {
  35666. var Action = (function () {
  35667. function Action(triggerOptions, condition) {
  35668. this.triggerOptions = triggerOptions;
  35669. if (triggerOptions.parameter) {
  35670. this.trigger = triggerOptions.trigger;
  35671. this._triggerParameter = triggerOptions.parameter;
  35672. }
  35673. else {
  35674. this.trigger = triggerOptions;
  35675. }
  35676. this._nextActiveAction = this;
  35677. this._condition = condition;
  35678. }
  35679. // Methods
  35680. Action.prototype._prepare = function () {
  35681. };
  35682. Action.prototype.getTriggerParameter = function () {
  35683. return this._triggerParameter;
  35684. };
  35685. Action.prototype._executeCurrent = function (evt) {
  35686. if (this._nextActiveAction._condition) {
  35687. var condition = this._nextActiveAction._condition;
  35688. var currentRenderId = this._actionManager.getScene().getRenderId();
  35689. // We cache the current evaluation for the current frame
  35690. if (condition._evaluationId === currentRenderId) {
  35691. if (!condition._currentResult) {
  35692. return;
  35693. }
  35694. }
  35695. else {
  35696. condition._evaluationId = currentRenderId;
  35697. if (!condition.isValid()) {
  35698. condition._currentResult = false;
  35699. return;
  35700. }
  35701. condition._currentResult = true;
  35702. }
  35703. }
  35704. this._nextActiveAction.execute(evt);
  35705. this.skipToNextActiveAction();
  35706. };
  35707. Action.prototype.execute = function (evt) {
  35708. };
  35709. Action.prototype.skipToNextActiveAction = function () {
  35710. if (this._nextActiveAction._child) {
  35711. if (!this._nextActiveAction._child._actionManager) {
  35712. this._nextActiveAction._child._actionManager = this._actionManager;
  35713. }
  35714. this._nextActiveAction = this._nextActiveAction._child;
  35715. }
  35716. else {
  35717. this._nextActiveAction = this;
  35718. }
  35719. };
  35720. Action.prototype.then = function (action) {
  35721. this._child = action;
  35722. action._actionManager = this._actionManager;
  35723. action._prepare();
  35724. return action;
  35725. };
  35726. Action.prototype._getProperty = function (propertyPath) {
  35727. return this._actionManager._getProperty(propertyPath);
  35728. };
  35729. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35730. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35731. };
  35732. Action.prototype.serialize = function (parent) {
  35733. };
  35734. // Called by BABYLON.Action objects in serialize(...). Internal use
  35735. Action.prototype._serialize = function (serializedAction, parent) {
  35736. var serializationObject = {
  35737. type: 1,
  35738. children: [],
  35739. name: serializedAction.name,
  35740. properties: serializedAction.properties || []
  35741. };
  35742. // Serialize child
  35743. if (this._child) {
  35744. this._child.serialize(serializationObject);
  35745. }
  35746. // Check if "this" has a condition
  35747. if (this._condition) {
  35748. var serializedCondition = this._condition.serialize();
  35749. serializedCondition.children.push(serializationObject);
  35750. if (parent) {
  35751. parent.children.push(serializedCondition);
  35752. }
  35753. return serializedCondition;
  35754. }
  35755. if (parent) {
  35756. parent.children.push(serializationObject);
  35757. }
  35758. return serializationObject;
  35759. };
  35760. return Action;
  35761. }());
  35762. Action._SerializeValueAsString = function (value) {
  35763. if (typeof value === "number") {
  35764. return value.toString();
  35765. }
  35766. if (typeof value === "boolean") {
  35767. return value ? "true" : "false";
  35768. }
  35769. if (value instanceof BABYLON.Vector2) {
  35770. return value.x + ", " + value.y;
  35771. }
  35772. if (value instanceof BABYLON.Vector3) {
  35773. return value.x + ", " + value.y + ", " + value.z;
  35774. }
  35775. if (value instanceof BABYLON.Color3) {
  35776. return value.r + ", " + value.g + ", " + value.b;
  35777. }
  35778. if (value instanceof BABYLON.Color4) {
  35779. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  35780. }
  35781. return value; // string
  35782. };
  35783. Action._GetTargetProperty = function (target) {
  35784. return {
  35785. name: "target",
  35786. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  35787. : target instanceof BABYLON.Light ? "LightProperties"
  35788. : target instanceof BABYLON.Camera ? "CameraProperties"
  35789. : "SceneProperties",
  35790. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  35791. };
  35792. };
  35793. BABYLON.Action = Action;
  35794. })(BABYLON || (BABYLON = {}));
  35795. //# sourceMappingURL=babylon.action.js.map
  35796. var BABYLON;
  35797. (function (BABYLON) {
  35798. /**
  35799. * ActionEvent is the event beint sent when an action is triggered.
  35800. */
  35801. var ActionEvent = (function () {
  35802. /**
  35803. * @constructor
  35804. * @param source The mesh or sprite that triggered the action.
  35805. * @param pointerX The X mouse cursor position at the time of the event
  35806. * @param pointerY The Y mouse cursor position at the time of the event
  35807. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  35808. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  35809. */
  35810. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  35811. this.source = source;
  35812. this.pointerX = pointerX;
  35813. this.pointerY = pointerY;
  35814. this.meshUnderPointer = meshUnderPointer;
  35815. this.sourceEvent = sourceEvent;
  35816. this.additionalData = additionalData;
  35817. }
  35818. /**
  35819. * Helper function to auto-create an ActionEvent from a source mesh.
  35820. * @param source The source mesh that triggered the event
  35821. * @param evt {Event} The original (browser) event
  35822. */
  35823. ActionEvent.CreateNew = function (source, evt, additionalData) {
  35824. var scene = source.getScene();
  35825. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35826. };
  35827. /**
  35828. * Helper function to auto-create an ActionEvent from a source mesh.
  35829. * @param source The source sprite that triggered the event
  35830. * @param scene Scene associated with the sprite
  35831. * @param evt {Event} The original (browser) event
  35832. */
  35833. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  35834. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35835. };
  35836. /**
  35837. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  35838. * @param scene the scene where the event occurred
  35839. * @param evt {Event} The original (browser) event
  35840. */
  35841. ActionEvent.CreateNewFromScene = function (scene, evt) {
  35842. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  35843. };
  35844. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  35845. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  35846. };
  35847. return ActionEvent;
  35848. }());
  35849. BABYLON.ActionEvent = ActionEvent;
  35850. /**
  35851. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  35852. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  35853. */
  35854. var ActionManager = (function () {
  35855. function ActionManager(scene) {
  35856. // Members
  35857. this.actions = new Array();
  35858. this.hoverCursor = '';
  35859. this._scene = scene;
  35860. scene._actionManagers.push(this);
  35861. }
  35862. Object.defineProperty(ActionManager, "NothingTrigger", {
  35863. get: function () {
  35864. return ActionManager._NothingTrigger;
  35865. },
  35866. enumerable: true,
  35867. configurable: true
  35868. });
  35869. Object.defineProperty(ActionManager, "OnPickTrigger", {
  35870. get: function () {
  35871. return ActionManager._OnPickTrigger;
  35872. },
  35873. enumerable: true,
  35874. configurable: true
  35875. });
  35876. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  35877. get: function () {
  35878. return ActionManager._OnLeftPickTrigger;
  35879. },
  35880. enumerable: true,
  35881. configurable: true
  35882. });
  35883. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  35884. get: function () {
  35885. return ActionManager._OnRightPickTrigger;
  35886. },
  35887. enumerable: true,
  35888. configurable: true
  35889. });
  35890. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  35891. get: function () {
  35892. return ActionManager._OnCenterPickTrigger;
  35893. },
  35894. enumerable: true,
  35895. configurable: true
  35896. });
  35897. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  35898. get: function () {
  35899. return ActionManager._OnPickDownTrigger;
  35900. },
  35901. enumerable: true,
  35902. configurable: true
  35903. });
  35904. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  35905. get: function () {
  35906. return ActionManager._OnDoublePickTrigger;
  35907. },
  35908. enumerable: true,
  35909. configurable: true
  35910. });
  35911. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  35912. get: function () {
  35913. return ActionManager._OnPickUpTrigger;
  35914. },
  35915. enumerable: true,
  35916. configurable: true
  35917. });
  35918. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  35919. /// This trigger will only be raised if you also declared a OnPickDown
  35920. get: function () {
  35921. return ActionManager._OnPickOutTrigger;
  35922. },
  35923. enumerable: true,
  35924. configurable: true
  35925. });
  35926. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  35927. get: function () {
  35928. return ActionManager._OnLongPressTrigger;
  35929. },
  35930. enumerable: true,
  35931. configurable: true
  35932. });
  35933. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  35934. get: function () {
  35935. return ActionManager._OnPointerOverTrigger;
  35936. },
  35937. enumerable: true,
  35938. configurable: true
  35939. });
  35940. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  35941. get: function () {
  35942. return ActionManager._OnPointerOutTrigger;
  35943. },
  35944. enumerable: true,
  35945. configurable: true
  35946. });
  35947. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  35948. get: function () {
  35949. return ActionManager._OnEveryFrameTrigger;
  35950. },
  35951. enumerable: true,
  35952. configurable: true
  35953. });
  35954. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  35955. get: function () {
  35956. return ActionManager._OnIntersectionEnterTrigger;
  35957. },
  35958. enumerable: true,
  35959. configurable: true
  35960. });
  35961. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  35962. get: function () {
  35963. return ActionManager._OnIntersectionExitTrigger;
  35964. },
  35965. enumerable: true,
  35966. configurable: true
  35967. });
  35968. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  35969. get: function () {
  35970. return ActionManager._OnKeyDownTrigger;
  35971. },
  35972. enumerable: true,
  35973. configurable: true
  35974. });
  35975. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  35976. get: function () {
  35977. return ActionManager._OnKeyUpTrigger;
  35978. },
  35979. enumerable: true,
  35980. configurable: true
  35981. });
  35982. // Methods
  35983. ActionManager.prototype.dispose = function () {
  35984. var index = this._scene._actionManagers.indexOf(this);
  35985. for (var i = 0; i < this.actions.length; i++) {
  35986. var action = this.actions[i];
  35987. ActionManager.Triggers[action.trigger]--;
  35988. if (ActionManager.Triggers[action.trigger] === 0) {
  35989. delete ActionManager.Triggers[action.trigger];
  35990. }
  35991. }
  35992. if (index > -1) {
  35993. this._scene._actionManagers.splice(index, 1);
  35994. }
  35995. };
  35996. ActionManager.prototype.getScene = function () {
  35997. return this._scene;
  35998. };
  35999. /**
  36000. * Does this action manager handles actions of any of the given triggers
  36001. * @param {number[]} triggers - the triggers to be tested
  36002. * @return {boolean} whether one (or more) of the triggers is handeled
  36003. */
  36004. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  36005. for (var index = 0; index < this.actions.length; index++) {
  36006. var action = this.actions[index];
  36007. if (triggers.indexOf(action.trigger) > -1) {
  36008. return true;
  36009. }
  36010. }
  36011. return false;
  36012. };
  36013. /**
  36014. * Does this action manager handles actions of a given trigger
  36015. * @param {number} trigger - the trigger to be tested
  36016. * @return {boolean} whether the trigger is handeled
  36017. */
  36018. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  36019. for (var index = 0; index < this.actions.length; index++) {
  36020. var action = this.actions[index];
  36021. if (action.trigger === trigger) {
  36022. return true;
  36023. }
  36024. }
  36025. return false;
  36026. };
  36027. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  36028. /**
  36029. * Does this action manager has pointer triggers
  36030. * @return {boolean} whether or not it has pointer triggers
  36031. */
  36032. get: function () {
  36033. for (var index = 0; index < this.actions.length; index++) {
  36034. var action = this.actions[index];
  36035. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  36036. return true;
  36037. }
  36038. }
  36039. return false;
  36040. },
  36041. enumerable: true,
  36042. configurable: true
  36043. });
  36044. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  36045. /**
  36046. * Does this action manager has pick triggers
  36047. * @return {boolean} whether or not it has pick triggers
  36048. */
  36049. get: function () {
  36050. for (var index = 0; index < this.actions.length; index++) {
  36051. var action = this.actions[index];
  36052. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  36053. return true;
  36054. }
  36055. }
  36056. return false;
  36057. },
  36058. enumerable: true,
  36059. configurable: true
  36060. });
  36061. Object.defineProperty(ActionManager, "HasTriggers", {
  36062. /**
  36063. * Does exist one action manager with at least one trigger
  36064. * @return {boolean} whether or not it exists one action manager with one trigger
  36065. **/
  36066. get: function () {
  36067. for (var t in ActionManager.Triggers) {
  36068. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36069. return true;
  36070. }
  36071. }
  36072. return false;
  36073. },
  36074. enumerable: true,
  36075. configurable: true
  36076. });
  36077. Object.defineProperty(ActionManager, "HasPickTriggers", {
  36078. /**
  36079. * Does exist one action manager with at least one pick trigger
  36080. * @return {boolean} whether or not it exists one action manager with one pick trigger
  36081. **/
  36082. get: function () {
  36083. for (var t in ActionManager.Triggers) {
  36084. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36085. var t_int = parseInt(t);
  36086. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  36087. return true;
  36088. }
  36089. }
  36090. }
  36091. return false;
  36092. },
  36093. enumerable: true,
  36094. configurable: true
  36095. });
  36096. /**
  36097. * Does exist one action manager that handles actions of a given trigger
  36098. * @param {number} trigger - the trigger to be tested
  36099. * @return {boolean} whether the trigger is handeled by at least one action manager
  36100. **/
  36101. ActionManager.HasSpecificTrigger = function (trigger) {
  36102. for (var t in ActionManager.Triggers) {
  36103. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36104. var t_int = parseInt(t);
  36105. if (t_int === trigger) {
  36106. return true;
  36107. }
  36108. }
  36109. }
  36110. return false;
  36111. };
  36112. /**
  36113. * Registers an action to this action manager
  36114. * @param {BABYLON.Action} action - the action to be registered
  36115. * @return {BABYLON.Action} the action amended (prepared) after registration
  36116. */
  36117. ActionManager.prototype.registerAction = function (action) {
  36118. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  36119. if (this.getScene().actionManager !== this) {
  36120. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  36121. return null;
  36122. }
  36123. }
  36124. this.actions.push(action);
  36125. if (ActionManager.Triggers[action.trigger]) {
  36126. ActionManager.Triggers[action.trigger]++;
  36127. }
  36128. else {
  36129. ActionManager.Triggers[action.trigger] = 1;
  36130. }
  36131. action._actionManager = this;
  36132. action._prepare();
  36133. return action;
  36134. };
  36135. /**
  36136. * Process a specific trigger
  36137. * @param {number} trigger - the trigger to process
  36138. * @param evt {BABYLON.ActionEvent} the event details to be processed
  36139. */
  36140. ActionManager.prototype.processTrigger = function (trigger, evt) {
  36141. for (var index = 0; index < this.actions.length; index++) {
  36142. var action = this.actions[index];
  36143. if (action.trigger === trigger) {
  36144. if (trigger === ActionManager.OnKeyUpTrigger
  36145. || trigger === ActionManager.OnKeyDownTrigger) {
  36146. var parameter = action.getTriggerParameter();
  36147. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  36148. if (!parameter.toLowerCase) {
  36149. continue;
  36150. }
  36151. var lowerCase = parameter.toLowerCase();
  36152. if (lowerCase !== evt.sourceEvent.key) {
  36153. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  36154. var actualkey = String.fromCharCode(unicode).toLowerCase();
  36155. if (actualkey !== lowerCase) {
  36156. continue;
  36157. }
  36158. }
  36159. }
  36160. }
  36161. action._executeCurrent(evt);
  36162. }
  36163. }
  36164. };
  36165. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  36166. var properties = propertyPath.split(".");
  36167. for (var index = 0; index < properties.length - 1; index++) {
  36168. target = target[properties[index]];
  36169. }
  36170. return target;
  36171. };
  36172. ActionManager.prototype._getProperty = function (propertyPath) {
  36173. var properties = propertyPath.split(".");
  36174. return properties[properties.length - 1];
  36175. };
  36176. ActionManager.prototype.serialize = function (name) {
  36177. var root = {
  36178. children: [],
  36179. name: name,
  36180. type: 3,
  36181. properties: [] // Empty for root but required
  36182. };
  36183. for (var i = 0; i < this.actions.length; i++) {
  36184. var triggerObject = {
  36185. type: 0,
  36186. children: [],
  36187. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  36188. properties: []
  36189. };
  36190. var triggerOptions = this.actions[i].triggerOptions;
  36191. if (triggerOptions && typeof triggerOptions !== "number") {
  36192. if (triggerOptions.parameter instanceof BABYLON.Node) {
  36193. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  36194. }
  36195. else {
  36196. var parameter = {};
  36197. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  36198. if (triggerOptions.parameter.mesh) {
  36199. parameter._meshId = triggerOptions.parameter.mesh.id;
  36200. }
  36201. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  36202. }
  36203. }
  36204. // Serialize child action, recursively
  36205. this.actions[i].serialize(triggerObject);
  36206. // Add serialized trigger
  36207. root.children.push(triggerObject);
  36208. }
  36209. return root;
  36210. };
  36211. ActionManager.Parse = function (parsedActions, object, scene) {
  36212. var actionManager = new BABYLON.ActionManager(scene);
  36213. if (object === null)
  36214. scene.actionManager = actionManager;
  36215. else
  36216. object.actionManager = actionManager;
  36217. // instanciate a new object
  36218. var instanciate = function (name, params) {
  36219. var newInstance = Object.create(BABYLON[name].prototype);
  36220. newInstance.constructor.apply(newInstance, params);
  36221. return newInstance;
  36222. };
  36223. var parseParameter = function (name, value, target, propertyPath) {
  36224. if (propertyPath === null) {
  36225. // String, boolean or float
  36226. var floatValue = parseFloat(value);
  36227. if (value === "true" || value === "false")
  36228. return value === "true";
  36229. else
  36230. return isNaN(floatValue) ? value : floatValue;
  36231. }
  36232. var effectiveTarget = propertyPath.split(".");
  36233. var values = value.split(",");
  36234. // Get effective Target
  36235. for (var i = 0; i < effectiveTarget.length; i++) {
  36236. target = target[effectiveTarget[i]];
  36237. }
  36238. // Return appropriate value with its type
  36239. if (typeof (target) === "boolean")
  36240. return values[0] === "true";
  36241. if (typeof (target) === "string")
  36242. return values[0];
  36243. // Parameters with multiple values such as Vector3 etc.
  36244. var split = new Array();
  36245. for (var i = 0; i < values.length; i++)
  36246. split.push(parseFloat(values[i]));
  36247. if (target instanceof BABYLON.Vector3)
  36248. return BABYLON.Vector3.FromArray(split);
  36249. if (target instanceof BABYLON.Vector4)
  36250. return BABYLON.Vector4.FromArray(split);
  36251. if (target instanceof BABYLON.Color3)
  36252. return BABYLON.Color3.FromArray(split);
  36253. if (target instanceof BABYLON.Color4)
  36254. return BABYLON.Color4.FromArray(split);
  36255. return parseFloat(values[0]);
  36256. };
  36257. // traverse graph per trigger
  36258. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  36259. if (combineArray === void 0) { combineArray = null; }
  36260. if (parsedAction.detached)
  36261. return;
  36262. var parameters = new Array();
  36263. var target = null;
  36264. var propertyPath = null;
  36265. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  36266. // Parameters
  36267. if (parsedAction.type === 2)
  36268. parameters.push(actionManager);
  36269. else
  36270. parameters.push(trigger);
  36271. if (combine) {
  36272. var actions = new Array();
  36273. for (var j = 0; j < parsedAction.combine.length; j++) {
  36274. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  36275. }
  36276. parameters.push(actions);
  36277. }
  36278. else {
  36279. for (var i = 0; i < parsedAction.properties.length; i++) {
  36280. var value = parsedAction.properties[i].value;
  36281. var name = parsedAction.properties[i].name;
  36282. var targetType = parsedAction.properties[i].targetType;
  36283. if (name === "target")
  36284. if (targetType !== null && targetType === "SceneProperties")
  36285. value = target = scene;
  36286. else
  36287. value = target = scene.getNodeByName(value);
  36288. else if (name === "parent")
  36289. value = scene.getNodeByName(value);
  36290. else if (name === "sound")
  36291. value = scene.getSoundByName(value);
  36292. else if (name !== "propertyPath") {
  36293. if (parsedAction.type === 2 && name === "operator")
  36294. value = BABYLON.ValueCondition[value];
  36295. else
  36296. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  36297. }
  36298. else {
  36299. propertyPath = value;
  36300. }
  36301. parameters.push(value);
  36302. }
  36303. }
  36304. if (combineArray === null) {
  36305. parameters.push(condition);
  36306. }
  36307. else {
  36308. parameters.push(null);
  36309. }
  36310. // If interpolate value action
  36311. if (parsedAction.name === "InterpolateValueAction") {
  36312. var param = parameters[parameters.length - 2];
  36313. parameters[parameters.length - 1] = param;
  36314. parameters[parameters.length - 2] = condition;
  36315. }
  36316. // Action or condition(s) and not CombineAction
  36317. var newAction = instanciate(parsedAction.name, parameters);
  36318. if (newAction instanceof BABYLON.Condition && condition !== null) {
  36319. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  36320. if (action)
  36321. action.then(nothing);
  36322. else
  36323. actionManager.registerAction(nothing);
  36324. action = nothing;
  36325. }
  36326. if (combineArray === null) {
  36327. if (newAction instanceof BABYLON.Condition) {
  36328. condition = newAction;
  36329. newAction = action;
  36330. }
  36331. else {
  36332. condition = null;
  36333. if (action)
  36334. action.then(newAction);
  36335. else
  36336. actionManager.registerAction(newAction);
  36337. }
  36338. }
  36339. else {
  36340. combineArray.push(newAction);
  36341. }
  36342. for (var i = 0; i < parsedAction.children.length; i++)
  36343. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  36344. };
  36345. // triggers
  36346. for (var i = 0; i < parsedActions.children.length; i++) {
  36347. var triggerParams;
  36348. var trigger = parsedActions.children[i];
  36349. if (trigger.properties.length > 0) {
  36350. var param = trigger.properties[0].value;
  36351. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  36352. if (value._meshId) {
  36353. value.mesh = scene.getMeshByID(value._meshId);
  36354. }
  36355. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  36356. }
  36357. else
  36358. triggerParams = BABYLON.ActionManager[trigger.name];
  36359. for (var j = 0; j < trigger.children.length; j++) {
  36360. if (!trigger.detached)
  36361. traverse(trigger.children[j], triggerParams, null, null);
  36362. }
  36363. }
  36364. };
  36365. ActionManager.GetTriggerName = function (trigger) {
  36366. switch (trigger) {
  36367. case 0: return "NothingTrigger";
  36368. case 1: return "OnPickTrigger";
  36369. case 2: return "OnLeftPickTrigger";
  36370. case 3: return "OnRightPickTrigger";
  36371. case 4: return "OnCenterPickTrigger";
  36372. case 5: return "OnPickDownTrigger";
  36373. case 6: return "OnPickUpTrigger";
  36374. case 7: return "OnLongPressTrigger";
  36375. case 8: return "OnPointerOverTrigger";
  36376. case 9: return "OnPointerOutTrigger";
  36377. case 10: return "OnEveryFrameTrigger";
  36378. case 11: return "OnIntersectionEnterTrigger";
  36379. case 12: return "OnIntersectionExitTrigger";
  36380. case 13: return "OnKeyDownTrigger";
  36381. case 14: return "OnKeyUpTrigger";
  36382. case 15: return "OnPickOutTrigger";
  36383. default: return "";
  36384. }
  36385. };
  36386. return ActionManager;
  36387. }());
  36388. // Statics
  36389. ActionManager._NothingTrigger = 0;
  36390. ActionManager._OnPickTrigger = 1;
  36391. ActionManager._OnLeftPickTrigger = 2;
  36392. ActionManager._OnRightPickTrigger = 3;
  36393. ActionManager._OnCenterPickTrigger = 4;
  36394. ActionManager._OnPickDownTrigger = 5;
  36395. ActionManager._OnDoublePickTrigger = 6;
  36396. ActionManager._OnPickUpTrigger = 7;
  36397. ActionManager._OnLongPressTrigger = 8;
  36398. ActionManager._OnPointerOverTrigger = 9;
  36399. ActionManager._OnPointerOutTrigger = 10;
  36400. ActionManager._OnEveryFrameTrigger = 11;
  36401. ActionManager._OnIntersectionEnterTrigger = 12;
  36402. ActionManager._OnIntersectionExitTrigger = 13;
  36403. ActionManager._OnKeyDownTrigger = 14;
  36404. ActionManager._OnKeyUpTrigger = 15;
  36405. ActionManager._OnPickOutTrigger = 16;
  36406. ActionManager.Triggers = {};
  36407. BABYLON.ActionManager = ActionManager;
  36408. })(BABYLON || (BABYLON = {}));
  36409. //# sourceMappingURL=babylon.actionManager.js.map
  36410. var BABYLON;
  36411. (function (BABYLON) {
  36412. var InterpolateValueAction = (function (_super) {
  36413. __extends(InterpolateValueAction, _super);
  36414. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  36415. if (duration === void 0) { duration = 1000; }
  36416. var _this = _super.call(this, triggerOptions, condition) || this;
  36417. _this.propertyPath = propertyPath;
  36418. _this.value = value;
  36419. _this.duration = duration;
  36420. _this.stopOtherAnimations = stopOtherAnimations;
  36421. _this.onInterpolationDone = onInterpolationDone;
  36422. _this._target = _this._effectiveTarget = target;
  36423. return _this;
  36424. }
  36425. InterpolateValueAction.prototype._prepare = function () {
  36426. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36427. this._property = this._getProperty(this.propertyPath);
  36428. };
  36429. InterpolateValueAction.prototype.execute = function () {
  36430. var scene = this._actionManager.getScene();
  36431. var keys = [
  36432. {
  36433. frame: 0,
  36434. value: this._effectiveTarget[this._property]
  36435. }, {
  36436. frame: 100,
  36437. value: this.value
  36438. }
  36439. ];
  36440. var dataType;
  36441. if (typeof this.value === "number") {
  36442. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  36443. }
  36444. else if (this.value instanceof BABYLON.Color3) {
  36445. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  36446. }
  36447. else if (this.value instanceof BABYLON.Vector3) {
  36448. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  36449. }
  36450. else if (this.value instanceof BABYLON.Matrix) {
  36451. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  36452. }
  36453. else if (this.value instanceof BABYLON.Quaternion) {
  36454. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  36455. }
  36456. else {
  36457. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  36458. return;
  36459. }
  36460. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36461. animation.setKeys(keys);
  36462. if (this.stopOtherAnimations) {
  36463. scene.stopAnimation(this._effectiveTarget);
  36464. }
  36465. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  36466. };
  36467. InterpolateValueAction.prototype.serialize = function (parent) {
  36468. return _super.prototype._serialize.call(this, {
  36469. name: "InterpolateValueAction",
  36470. properties: [
  36471. BABYLON.Action._GetTargetProperty(this._target),
  36472. { name: "propertyPath", value: this.propertyPath },
  36473. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36474. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  36475. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  36476. ]
  36477. }, parent);
  36478. };
  36479. return InterpolateValueAction;
  36480. }(BABYLON.Action));
  36481. BABYLON.InterpolateValueAction = InterpolateValueAction;
  36482. })(BABYLON || (BABYLON = {}));
  36483. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  36484. var BABYLON;
  36485. (function (BABYLON) {
  36486. var SwitchBooleanAction = (function (_super) {
  36487. __extends(SwitchBooleanAction, _super);
  36488. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  36489. var _this = _super.call(this, triggerOptions, condition) || this;
  36490. _this.propertyPath = propertyPath;
  36491. _this._target = _this._effectiveTarget = target;
  36492. return _this;
  36493. }
  36494. SwitchBooleanAction.prototype._prepare = function () {
  36495. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36496. this._property = this._getProperty(this.propertyPath);
  36497. };
  36498. SwitchBooleanAction.prototype.execute = function () {
  36499. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  36500. };
  36501. SwitchBooleanAction.prototype.serialize = function (parent) {
  36502. return _super.prototype._serialize.call(this, {
  36503. name: "SwitchBooleanAction",
  36504. properties: [
  36505. BABYLON.Action._GetTargetProperty(this._target),
  36506. { name: "propertyPath", value: this.propertyPath }
  36507. ]
  36508. }, parent);
  36509. };
  36510. return SwitchBooleanAction;
  36511. }(BABYLON.Action));
  36512. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  36513. var SetStateAction = (function (_super) {
  36514. __extends(SetStateAction, _super);
  36515. function SetStateAction(triggerOptions, target, value, condition) {
  36516. var _this = _super.call(this, triggerOptions, condition) || this;
  36517. _this.value = value;
  36518. _this._target = target;
  36519. return _this;
  36520. }
  36521. SetStateAction.prototype.execute = function () {
  36522. this._target.state = this.value;
  36523. };
  36524. SetStateAction.prototype.serialize = function (parent) {
  36525. return _super.prototype._serialize.call(this, {
  36526. name: "SetStateAction",
  36527. properties: [
  36528. BABYLON.Action._GetTargetProperty(this._target),
  36529. { name: "value", value: this.value }
  36530. ]
  36531. }, parent);
  36532. };
  36533. return SetStateAction;
  36534. }(BABYLON.Action));
  36535. BABYLON.SetStateAction = SetStateAction;
  36536. var SetValueAction = (function (_super) {
  36537. __extends(SetValueAction, _super);
  36538. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  36539. var _this = _super.call(this, triggerOptions, condition) || this;
  36540. _this.propertyPath = propertyPath;
  36541. _this.value = value;
  36542. _this._target = _this._effectiveTarget = target;
  36543. return _this;
  36544. }
  36545. SetValueAction.prototype._prepare = function () {
  36546. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36547. this._property = this._getProperty(this.propertyPath);
  36548. };
  36549. SetValueAction.prototype.execute = function () {
  36550. this._effectiveTarget[this._property] = this.value;
  36551. if (this._target.markAsDirty) {
  36552. this._target.markAsDirty(this._property);
  36553. }
  36554. };
  36555. SetValueAction.prototype.serialize = function (parent) {
  36556. return _super.prototype._serialize.call(this, {
  36557. name: "SetValueAction",
  36558. properties: [
  36559. BABYLON.Action._GetTargetProperty(this._target),
  36560. { name: "propertyPath", value: this.propertyPath },
  36561. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36562. ]
  36563. }, parent);
  36564. };
  36565. return SetValueAction;
  36566. }(BABYLON.Action));
  36567. BABYLON.SetValueAction = SetValueAction;
  36568. var IncrementValueAction = (function (_super) {
  36569. __extends(IncrementValueAction, _super);
  36570. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  36571. var _this = _super.call(this, triggerOptions, condition) || this;
  36572. _this.propertyPath = propertyPath;
  36573. _this.value = value;
  36574. _this._target = _this._effectiveTarget = target;
  36575. return _this;
  36576. }
  36577. IncrementValueAction.prototype._prepare = function () {
  36578. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36579. this._property = this._getProperty(this.propertyPath);
  36580. if (typeof this._effectiveTarget[this._property] !== "number") {
  36581. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  36582. }
  36583. };
  36584. IncrementValueAction.prototype.execute = function () {
  36585. this._effectiveTarget[this._property] += this.value;
  36586. if (this._target.markAsDirty) {
  36587. this._target.markAsDirty(this._property);
  36588. }
  36589. };
  36590. IncrementValueAction.prototype.serialize = function (parent) {
  36591. return _super.prototype._serialize.call(this, {
  36592. name: "IncrementValueAction",
  36593. properties: [
  36594. BABYLON.Action._GetTargetProperty(this._target),
  36595. { name: "propertyPath", value: this.propertyPath },
  36596. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36597. ]
  36598. }, parent);
  36599. };
  36600. return IncrementValueAction;
  36601. }(BABYLON.Action));
  36602. BABYLON.IncrementValueAction = IncrementValueAction;
  36603. var PlayAnimationAction = (function (_super) {
  36604. __extends(PlayAnimationAction, _super);
  36605. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  36606. var _this = _super.call(this, triggerOptions, condition) || this;
  36607. _this.from = from;
  36608. _this.to = to;
  36609. _this.loop = loop;
  36610. _this._target = target;
  36611. return _this;
  36612. }
  36613. PlayAnimationAction.prototype._prepare = function () {
  36614. };
  36615. PlayAnimationAction.prototype.execute = function () {
  36616. var scene = this._actionManager.getScene();
  36617. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  36618. };
  36619. PlayAnimationAction.prototype.serialize = function (parent) {
  36620. return _super.prototype._serialize.call(this, {
  36621. name: "PlayAnimationAction",
  36622. properties: [
  36623. BABYLON.Action._GetTargetProperty(this._target),
  36624. { name: "from", value: String(this.from) },
  36625. { name: "to", value: String(this.to) },
  36626. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  36627. ]
  36628. }, parent);
  36629. };
  36630. return PlayAnimationAction;
  36631. }(BABYLON.Action));
  36632. BABYLON.PlayAnimationAction = PlayAnimationAction;
  36633. var StopAnimationAction = (function (_super) {
  36634. __extends(StopAnimationAction, _super);
  36635. function StopAnimationAction(triggerOptions, target, condition) {
  36636. var _this = _super.call(this, triggerOptions, condition) || this;
  36637. _this._target = target;
  36638. return _this;
  36639. }
  36640. StopAnimationAction.prototype._prepare = function () {
  36641. };
  36642. StopAnimationAction.prototype.execute = function () {
  36643. var scene = this._actionManager.getScene();
  36644. scene.stopAnimation(this._target);
  36645. };
  36646. StopAnimationAction.prototype.serialize = function (parent) {
  36647. return _super.prototype._serialize.call(this, {
  36648. name: "StopAnimationAction",
  36649. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  36650. }, parent);
  36651. };
  36652. return StopAnimationAction;
  36653. }(BABYLON.Action));
  36654. BABYLON.StopAnimationAction = StopAnimationAction;
  36655. var DoNothingAction = (function (_super) {
  36656. __extends(DoNothingAction, _super);
  36657. function DoNothingAction(triggerOptions, condition) {
  36658. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  36659. return _super.call(this, triggerOptions, condition) || this;
  36660. }
  36661. DoNothingAction.prototype.execute = function () {
  36662. };
  36663. DoNothingAction.prototype.serialize = function (parent) {
  36664. return _super.prototype._serialize.call(this, {
  36665. name: "DoNothingAction",
  36666. properties: []
  36667. }, parent);
  36668. };
  36669. return DoNothingAction;
  36670. }(BABYLON.Action));
  36671. BABYLON.DoNothingAction = DoNothingAction;
  36672. var CombineAction = (function (_super) {
  36673. __extends(CombineAction, _super);
  36674. function CombineAction(triggerOptions, children, condition) {
  36675. var _this = _super.call(this, triggerOptions, condition) || this;
  36676. _this.children = children;
  36677. return _this;
  36678. }
  36679. CombineAction.prototype._prepare = function () {
  36680. for (var index = 0; index < this.children.length; index++) {
  36681. this.children[index]._actionManager = this._actionManager;
  36682. this.children[index]._prepare();
  36683. }
  36684. };
  36685. CombineAction.prototype.execute = function (evt) {
  36686. for (var index = 0; index < this.children.length; index++) {
  36687. this.children[index].execute(evt);
  36688. }
  36689. };
  36690. CombineAction.prototype.serialize = function (parent) {
  36691. var serializationObject = _super.prototype._serialize.call(this, {
  36692. name: "CombineAction",
  36693. properties: [],
  36694. combine: []
  36695. }, parent);
  36696. for (var i = 0; i < this.children.length; i++) {
  36697. serializationObject.combine.push(this.children[i].serialize(null));
  36698. }
  36699. return serializationObject;
  36700. };
  36701. return CombineAction;
  36702. }(BABYLON.Action));
  36703. BABYLON.CombineAction = CombineAction;
  36704. var ExecuteCodeAction = (function (_super) {
  36705. __extends(ExecuteCodeAction, _super);
  36706. function ExecuteCodeAction(triggerOptions, func, condition) {
  36707. var _this = _super.call(this, triggerOptions, condition) || this;
  36708. _this.func = func;
  36709. return _this;
  36710. }
  36711. ExecuteCodeAction.prototype.execute = function (evt) {
  36712. this.func(evt);
  36713. };
  36714. return ExecuteCodeAction;
  36715. }(BABYLON.Action));
  36716. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  36717. var SetParentAction = (function (_super) {
  36718. __extends(SetParentAction, _super);
  36719. function SetParentAction(triggerOptions, target, parent, condition) {
  36720. var _this = _super.call(this, triggerOptions, condition) || this;
  36721. _this._target = target;
  36722. _this._parent = parent;
  36723. return _this;
  36724. }
  36725. SetParentAction.prototype._prepare = function () {
  36726. };
  36727. SetParentAction.prototype.execute = function () {
  36728. if (this._target.parent === this._parent) {
  36729. return;
  36730. }
  36731. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  36732. invertParentWorldMatrix.invert();
  36733. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  36734. this._target.parent = this._parent;
  36735. };
  36736. SetParentAction.prototype.serialize = function (parent) {
  36737. return _super.prototype._serialize.call(this, {
  36738. name: "SetParentAction",
  36739. properties: [
  36740. BABYLON.Action._GetTargetProperty(this._target),
  36741. BABYLON.Action._GetTargetProperty(this._parent),
  36742. ]
  36743. }, parent);
  36744. };
  36745. return SetParentAction;
  36746. }(BABYLON.Action));
  36747. BABYLON.SetParentAction = SetParentAction;
  36748. var PlaySoundAction = (function (_super) {
  36749. __extends(PlaySoundAction, _super);
  36750. function PlaySoundAction(triggerOptions, sound, condition) {
  36751. var _this = _super.call(this, triggerOptions, condition) || this;
  36752. _this._sound = sound;
  36753. return _this;
  36754. }
  36755. PlaySoundAction.prototype._prepare = function () {
  36756. };
  36757. PlaySoundAction.prototype.execute = function () {
  36758. if (this._sound !== undefined)
  36759. this._sound.play();
  36760. };
  36761. PlaySoundAction.prototype.serialize = function (parent) {
  36762. return _super.prototype._serialize.call(this, {
  36763. name: "PlaySoundAction",
  36764. properties: [{ name: "sound", value: this._sound.name }]
  36765. }, parent);
  36766. };
  36767. return PlaySoundAction;
  36768. }(BABYLON.Action));
  36769. BABYLON.PlaySoundAction = PlaySoundAction;
  36770. var StopSoundAction = (function (_super) {
  36771. __extends(StopSoundAction, _super);
  36772. function StopSoundAction(triggerOptions, sound, condition) {
  36773. var _this = _super.call(this, triggerOptions, condition) || this;
  36774. _this._sound = sound;
  36775. return _this;
  36776. }
  36777. StopSoundAction.prototype._prepare = function () {
  36778. };
  36779. StopSoundAction.prototype.execute = function () {
  36780. if (this._sound !== undefined)
  36781. this._sound.stop();
  36782. };
  36783. StopSoundAction.prototype.serialize = function (parent) {
  36784. return _super.prototype._serialize.call(this, {
  36785. name: "StopSoundAction",
  36786. properties: [{ name: "sound", value: this._sound.name }]
  36787. }, parent);
  36788. };
  36789. return StopSoundAction;
  36790. }(BABYLON.Action));
  36791. BABYLON.StopSoundAction = StopSoundAction;
  36792. })(BABYLON || (BABYLON = {}));
  36793. //# sourceMappingURL=babylon.directActions.js.map
  36794. var BABYLON;
  36795. (function (BABYLON) {
  36796. var SpriteManager = (function () {
  36797. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  36798. if (epsilon === void 0) { epsilon = 0.01; }
  36799. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36800. this.name = name;
  36801. this.sprites = new Array();
  36802. this.renderingGroupId = 0;
  36803. this.layerMask = 0x0FFFFFFF;
  36804. this.fogEnabled = true;
  36805. this.isPickable = false;
  36806. /**
  36807. * An event triggered when the manager is disposed.
  36808. * @type {BABYLON.Observable}
  36809. */
  36810. this.onDisposeObservable = new BABYLON.Observable();
  36811. this._vertexBuffers = {};
  36812. this._capacity = capacity;
  36813. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  36814. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36815. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36816. if (cellSize.width && cellSize.height) {
  36817. this.cellWidth = cellSize.width;
  36818. this.cellHeight = cellSize.height;
  36819. }
  36820. else if (cellSize !== undefined) {
  36821. this.cellWidth = cellSize;
  36822. this.cellHeight = cellSize;
  36823. }
  36824. else {
  36825. return;
  36826. }
  36827. this._epsilon = epsilon;
  36828. this._scene = scene;
  36829. this._scene.spriteManagers.push(this);
  36830. var indices = [];
  36831. var index = 0;
  36832. for (var count = 0; count < capacity; count++) {
  36833. indices.push(index);
  36834. indices.push(index + 1);
  36835. indices.push(index + 2);
  36836. indices.push(index);
  36837. indices.push(index + 2);
  36838. indices.push(index + 3);
  36839. index += 4;
  36840. }
  36841. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  36842. // VBO
  36843. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  36844. this._vertexData = new Float32Array(capacity * 16 * 4);
  36845. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  36846. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  36847. var options = this._buffer.createVertexBuffer("options", 4, 4);
  36848. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  36849. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  36850. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  36851. this._vertexBuffers["options"] = options;
  36852. this._vertexBuffers["cellInfo"] = cellInfo;
  36853. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  36854. // Effects
  36855. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  36856. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  36857. }
  36858. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  36859. set: function (callback) {
  36860. if (this._onDisposeObserver) {
  36861. this.onDisposeObservable.remove(this._onDisposeObserver);
  36862. }
  36863. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36864. },
  36865. enumerable: true,
  36866. configurable: true
  36867. });
  36868. Object.defineProperty(SpriteManager.prototype, "texture", {
  36869. get: function () {
  36870. return this._spriteTexture;
  36871. },
  36872. set: function (value) {
  36873. this._spriteTexture = value;
  36874. },
  36875. enumerable: true,
  36876. configurable: true
  36877. });
  36878. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  36879. var arrayOffset = index * 16;
  36880. if (offsetX === 0)
  36881. offsetX = this._epsilon;
  36882. else if (offsetX === 1)
  36883. offsetX = 1 - this._epsilon;
  36884. if (offsetY === 0)
  36885. offsetY = this._epsilon;
  36886. else if (offsetY === 1)
  36887. offsetY = 1 - this._epsilon;
  36888. this._vertexData[arrayOffset] = sprite.position.x;
  36889. this._vertexData[arrayOffset + 1] = sprite.position.y;
  36890. this._vertexData[arrayOffset + 2] = sprite.position.z;
  36891. this._vertexData[arrayOffset + 3] = sprite.angle;
  36892. this._vertexData[arrayOffset + 4] = sprite.width;
  36893. this._vertexData[arrayOffset + 5] = sprite.height;
  36894. this._vertexData[arrayOffset + 6] = offsetX;
  36895. this._vertexData[arrayOffset + 7] = offsetY;
  36896. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  36897. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  36898. var offset = (sprite.cellIndex / rowSize) >> 0;
  36899. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  36900. this._vertexData[arrayOffset + 11] = offset;
  36901. // Color
  36902. this._vertexData[arrayOffset + 12] = sprite.color.r;
  36903. this._vertexData[arrayOffset + 13] = sprite.color.g;
  36904. this._vertexData[arrayOffset + 14] = sprite.color.b;
  36905. this._vertexData[arrayOffset + 15] = sprite.color.a;
  36906. };
  36907. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  36908. var count = Math.min(this._capacity, this.sprites.length);
  36909. var min = BABYLON.Vector3.Zero();
  36910. var max = BABYLON.Vector3.Zero();
  36911. var distance = Number.MAX_VALUE;
  36912. var currentSprite;
  36913. var cameraSpacePosition = BABYLON.Vector3.Zero();
  36914. var cameraView = camera.getViewMatrix();
  36915. for (var index = 0; index < count; index++) {
  36916. var sprite = this.sprites[index];
  36917. if (!sprite) {
  36918. continue;
  36919. }
  36920. if (predicate) {
  36921. if (!predicate(sprite)) {
  36922. continue;
  36923. }
  36924. }
  36925. else if (!sprite.isPickable) {
  36926. continue;
  36927. }
  36928. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  36929. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  36930. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  36931. if (ray.intersectsBoxMinMax(min, max)) {
  36932. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  36933. if (distance > currentDistance) {
  36934. distance = currentDistance;
  36935. currentSprite = sprite;
  36936. if (fastCheck) {
  36937. break;
  36938. }
  36939. }
  36940. }
  36941. }
  36942. if (currentSprite) {
  36943. var result = new BABYLON.PickingInfo();
  36944. result.hit = true;
  36945. result.pickedSprite = currentSprite;
  36946. result.distance = distance;
  36947. return result;
  36948. }
  36949. return null;
  36950. };
  36951. SpriteManager.prototype.render = function () {
  36952. // Check
  36953. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  36954. return;
  36955. var engine = this._scene.getEngine();
  36956. var baseSize = this._spriteTexture.getBaseSize();
  36957. // Sprites
  36958. var deltaTime = engine.getDeltaTime();
  36959. var max = Math.min(this._capacity, this.sprites.length);
  36960. var rowSize = baseSize.width / this.cellWidth;
  36961. var offset = 0;
  36962. for (var index = 0; index < max; index++) {
  36963. var sprite = this.sprites[index];
  36964. if (!sprite) {
  36965. continue;
  36966. }
  36967. sprite._animate(deltaTime);
  36968. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  36969. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  36970. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  36971. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  36972. }
  36973. this._buffer.update(this._vertexData);
  36974. // Render
  36975. var effect = this._effectBase;
  36976. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  36977. effect = this._effectFog;
  36978. }
  36979. engine.enableEffect(effect);
  36980. var viewMatrix = this._scene.getViewMatrix();
  36981. effect.setTexture("diffuseSampler", this._spriteTexture);
  36982. effect.setMatrix("view", viewMatrix);
  36983. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  36984. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  36985. // Fog
  36986. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  36987. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  36988. effect.setColor3("vFogColor", this._scene.fogColor);
  36989. }
  36990. // VBOs
  36991. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36992. // Draw order
  36993. engine.setDepthFunctionToLessOrEqual();
  36994. effect.setBool("alphaTest", true);
  36995. engine.setColorWrite(false);
  36996. engine.draw(true, 0, max * 6);
  36997. engine.setColorWrite(true);
  36998. effect.setBool("alphaTest", false);
  36999. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  37000. engine.draw(true, 0, max * 6);
  37001. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37002. };
  37003. SpriteManager.prototype.dispose = function () {
  37004. if (this._buffer) {
  37005. this._buffer.dispose();
  37006. this._buffer = null;
  37007. }
  37008. if (this._indexBuffer) {
  37009. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37010. this._indexBuffer = null;
  37011. }
  37012. if (this._spriteTexture) {
  37013. this._spriteTexture.dispose();
  37014. this._spriteTexture = null;
  37015. }
  37016. // Remove from scene
  37017. var index = this._scene.spriteManagers.indexOf(this);
  37018. this._scene.spriteManagers.splice(index, 1);
  37019. // Callback
  37020. this.onDisposeObservable.notifyObservers(this);
  37021. this.onDisposeObservable.clear();
  37022. };
  37023. return SpriteManager;
  37024. }());
  37025. BABYLON.SpriteManager = SpriteManager;
  37026. })(BABYLON || (BABYLON = {}));
  37027. //# sourceMappingURL=babylon.spriteManager.js.map
  37028. var BABYLON;
  37029. (function (BABYLON) {
  37030. var Sprite = (function () {
  37031. function Sprite(name, manager) {
  37032. this.name = name;
  37033. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37034. this.width = 1.0;
  37035. this.height = 1.0;
  37036. this.angle = 0;
  37037. this.cellIndex = 0;
  37038. this.invertU = 0;
  37039. this.invertV = 0;
  37040. this.animations = new Array();
  37041. this.isPickable = false;
  37042. this._animationStarted = false;
  37043. this._loopAnimation = false;
  37044. this._fromIndex = 0;
  37045. this._toIndex = 0;
  37046. this._delay = 0;
  37047. this._direction = 1;
  37048. this._frameCount = 0;
  37049. this._time = 0;
  37050. this._manager = manager;
  37051. this._manager.sprites.push(this);
  37052. this.position = BABYLON.Vector3.Zero();
  37053. }
  37054. Object.defineProperty(Sprite.prototype, "size", {
  37055. get: function () {
  37056. return this.width;
  37057. },
  37058. set: function (value) {
  37059. this.width = value;
  37060. this.height = value;
  37061. },
  37062. enumerable: true,
  37063. configurable: true
  37064. });
  37065. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  37066. this._fromIndex = from;
  37067. this._toIndex = to;
  37068. this._loopAnimation = loop;
  37069. this._delay = delay;
  37070. this._animationStarted = true;
  37071. this._direction = from < to ? 1 : -1;
  37072. this.cellIndex = from;
  37073. this._time = 0;
  37074. this._onAnimationEnd = onAnimationEnd;
  37075. };
  37076. Sprite.prototype.stopAnimation = function () {
  37077. this._animationStarted = false;
  37078. };
  37079. Sprite.prototype._animate = function (deltaTime) {
  37080. if (!this._animationStarted)
  37081. return;
  37082. this._time += deltaTime;
  37083. if (this._time > this._delay) {
  37084. this._time = this._time % this._delay;
  37085. this.cellIndex += this._direction;
  37086. if (this.cellIndex === this._toIndex) {
  37087. if (this._loopAnimation) {
  37088. this.cellIndex = this._fromIndex;
  37089. }
  37090. else {
  37091. this._animationStarted = false;
  37092. if (this._onAnimationEnd) {
  37093. this._onAnimationEnd();
  37094. }
  37095. if (this.disposeWhenFinishedAnimating) {
  37096. this.dispose();
  37097. }
  37098. }
  37099. }
  37100. }
  37101. };
  37102. Sprite.prototype.dispose = function () {
  37103. for (var i = 0; i < this._manager.sprites.length; i++) {
  37104. if (this._manager.sprites[i] == this) {
  37105. this._manager.sprites.splice(i, 1);
  37106. }
  37107. }
  37108. };
  37109. return Sprite;
  37110. }());
  37111. BABYLON.Sprite = Sprite;
  37112. })(BABYLON || (BABYLON = {}));
  37113. //# sourceMappingURL=babylon.sprite.js.map
  37114. var BABYLON;
  37115. (function (BABYLON) {
  37116. var IntersectionInfo = (function () {
  37117. function IntersectionInfo(bu, bv, distance) {
  37118. this.bu = bu;
  37119. this.bv = bv;
  37120. this.distance = distance;
  37121. this.faceId = 0;
  37122. this.subMeshId = 0;
  37123. }
  37124. return IntersectionInfo;
  37125. }());
  37126. BABYLON.IntersectionInfo = IntersectionInfo;
  37127. var PickingInfo = (function () {
  37128. function PickingInfo() {
  37129. this.hit = false;
  37130. this.distance = 0;
  37131. this.pickedPoint = null;
  37132. this.pickedMesh = null;
  37133. this.bu = 0;
  37134. this.bv = 0;
  37135. this.faceId = -1;
  37136. this.subMeshId = 0;
  37137. this.pickedSprite = null;
  37138. }
  37139. // Methods
  37140. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  37141. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  37142. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  37143. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37144. return null;
  37145. }
  37146. var indices = this.pickedMesh.getIndices();
  37147. var result;
  37148. if (useVerticesNormals) {
  37149. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37150. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  37151. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  37152. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  37153. normal0 = normal0.scale(this.bu);
  37154. normal1 = normal1.scale(this.bv);
  37155. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  37156. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  37157. }
  37158. else {
  37159. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37160. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  37161. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  37162. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  37163. var p1p2 = vertex1.subtract(vertex2);
  37164. var p3p2 = vertex3.subtract(vertex2);
  37165. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  37166. }
  37167. if (useWorldCoordinates) {
  37168. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  37169. }
  37170. return BABYLON.Vector3.Normalize(result);
  37171. };
  37172. PickingInfo.prototype.getTextureCoordinates = function () {
  37173. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37174. return null;
  37175. }
  37176. var indices = this.pickedMesh.getIndices();
  37177. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37178. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  37179. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  37180. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  37181. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  37182. uv1 = uv1.scale(this.bu);
  37183. uv2 = uv2.scale(this.bv);
  37184. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  37185. };
  37186. return PickingInfo;
  37187. }());
  37188. BABYLON.PickingInfo = PickingInfo;
  37189. })(BABYLON || (BABYLON = {}));
  37190. //# sourceMappingURL=babylon.pickingInfo.js.map
  37191. var BABYLON;
  37192. (function (BABYLON) {
  37193. var Ray = (function () {
  37194. function Ray(origin, direction, length) {
  37195. if (length === void 0) { length = Number.MAX_VALUE; }
  37196. this.origin = origin;
  37197. this.direction = direction;
  37198. this.length = length;
  37199. }
  37200. // Methods
  37201. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  37202. var d = 0.0;
  37203. var maxValue = Number.MAX_VALUE;
  37204. var inv;
  37205. var min;
  37206. var max;
  37207. var temp;
  37208. if (Math.abs(this.direction.x) < 0.0000001) {
  37209. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  37210. return false;
  37211. }
  37212. }
  37213. else {
  37214. inv = 1.0 / this.direction.x;
  37215. min = (minimum.x - this.origin.x) * inv;
  37216. max = (maximum.x - this.origin.x) * inv;
  37217. if (max === -Infinity) {
  37218. max = Infinity;
  37219. }
  37220. if (min > max) {
  37221. temp = min;
  37222. min = max;
  37223. max = temp;
  37224. }
  37225. d = Math.max(min, d);
  37226. maxValue = Math.min(max, maxValue);
  37227. if (d > maxValue) {
  37228. return false;
  37229. }
  37230. }
  37231. if (Math.abs(this.direction.y) < 0.0000001) {
  37232. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  37233. return false;
  37234. }
  37235. }
  37236. else {
  37237. inv = 1.0 / this.direction.y;
  37238. min = (minimum.y - this.origin.y) * inv;
  37239. max = (maximum.y - this.origin.y) * inv;
  37240. if (max === -Infinity) {
  37241. max = Infinity;
  37242. }
  37243. if (min > max) {
  37244. temp = min;
  37245. min = max;
  37246. max = temp;
  37247. }
  37248. d = Math.max(min, d);
  37249. maxValue = Math.min(max, maxValue);
  37250. if (d > maxValue) {
  37251. return false;
  37252. }
  37253. }
  37254. if (Math.abs(this.direction.z) < 0.0000001) {
  37255. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  37256. return false;
  37257. }
  37258. }
  37259. else {
  37260. inv = 1.0 / this.direction.z;
  37261. min = (minimum.z - this.origin.z) * inv;
  37262. max = (maximum.z - this.origin.z) * inv;
  37263. if (max === -Infinity) {
  37264. max = Infinity;
  37265. }
  37266. if (min > max) {
  37267. temp = min;
  37268. min = max;
  37269. max = temp;
  37270. }
  37271. d = Math.max(min, d);
  37272. maxValue = Math.min(max, maxValue);
  37273. if (d > maxValue) {
  37274. return false;
  37275. }
  37276. }
  37277. return true;
  37278. };
  37279. Ray.prototype.intersectsBox = function (box) {
  37280. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  37281. };
  37282. Ray.prototype.intersectsSphere = function (sphere) {
  37283. var x = sphere.center.x - this.origin.x;
  37284. var y = sphere.center.y - this.origin.y;
  37285. var z = sphere.center.z - this.origin.z;
  37286. var pyth = (x * x) + (y * y) + (z * z);
  37287. var rr = sphere.radius * sphere.radius;
  37288. if (pyth <= rr) {
  37289. return true;
  37290. }
  37291. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  37292. if (dot < 0.0) {
  37293. return false;
  37294. }
  37295. var temp = pyth - (dot * dot);
  37296. return temp <= rr;
  37297. };
  37298. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  37299. if (!this._edge1) {
  37300. this._edge1 = BABYLON.Vector3.Zero();
  37301. this._edge2 = BABYLON.Vector3.Zero();
  37302. this._pvec = BABYLON.Vector3.Zero();
  37303. this._tvec = BABYLON.Vector3.Zero();
  37304. this._qvec = BABYLON.Vector3.Zero();
  37305. }
  37306. vertex1.subtractToRef(vertex0, this._edge1);
  37307. vertex2.subtractToRef(vertex0, this._edge2);
  37308. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  37309. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  37310. if (det === 0) {
  37311. return null;
  37312. }
  37313. var invdet = 1 / det;
  37314. this.origin.subtractToRef(vertex0, this._tvec);
  37315. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  37316. if (bu < 0 || bu > 1.0) {
  37317. return null;
  37318. }
  37319. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  37320. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  37321. if (bv < 0 || bu + bv > 1.0) {
  37322. return null;
  37323. }
  37324. //check if the distance is longer than the predefined length.
  37325. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  37326. if (distance > this.length) {
  37327. return null;
  37328. }
  37329. return new BABYLON.IntersectionInfo(bu, bv, distance);
  37330. };
  37331. Ray.prototype.intersectsPlane = function (plane) {
  37332. var distance;
  37333. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  37334. if (Math.abs(result1) < 9.99999997475243E-07) {
  37335. return null;
  37336. }
  37337. else {
  37338. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  37339. distance = (-plane.d - result2) / result1;
  37340. if (distance < 0.0) {
  37341. if (distance < -9.99999997475243E-07) {
  37342. return null;
  37343. }
  37344. else {
  37345. return 0;
  37346. }
  37347. }
  37348. return distance;
  37349. }
  37350. };
  37351. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  37352. var tm = BABYLON.Tmp.Matrix[0];
  37353. mesh.getWorldMatrix().invertToRef(tm);
  37354. if (this._tmpRay) {
  37355. Ray.TransformToRef(this, tm, this._tmpRay);
  37356. }
  37357. else {
  37358. this._tmpRay = Ray.Transform(this, tm);
  37359. }
  37360. return mesh.intersects(this._tmpRay, fastCheck);
  37361. };
  37362. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  37363. if (results) {
  37364. results.length = 0;
  37365. }
  37366. else {
  37367. results = [];
  37368. }
  37369. for (var i = 0; i < meshes.length; i++) {
  37370. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  37371. if (pickInfo.hit) {
  37372. results.push(pickInfo);
  37373. }
  37374. }
  37375. results.sort(this._comparePickingInfo);
  37376. return results;
  37377. };
  37378. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  37379. if (pickingInfoA.distance < pickingInfoB.distance) {
  37380. return -1;
  37381. }
  37382. else if (pickingInfoA.distance > pickingInfoB.distance) {
  37383. return 1;
  37384. }
  37385. else {
  37386. return 0;
  37387. }
  37388. };
  37389. /**
  37390. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  37391. * @param sega the first point of the segment to test the intersection against
  37392. * @param segb the second point of the segment to test the intersection against
  37393. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  37394. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  37395. */
  37396. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  37397. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  37398. var u = segb.subtract(sega);
  37399. var v = rsegb.subtract(this.origin);
  37400. var w = sega.subtract(this.origin);
  37401. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  37402. var b = BABYLON.Vector3.Dot(u, v);
  37403. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  37404. var d = BABYLON.Vector3.Dot(u, w);
  37405. var e = BABYLON.Vector3.Dot(v, w);
  37406. var D = a * c - b * b; // always >= 0
  37407. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  37408. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  37409. // compute the line parameters of the two closest points
  37410. if (D < Ray.smallnum) {
  37411. sN = 0.0; // force using point P0 on segment S1
  37412. sD = 1.0; // to prevent possible division by 0.0 later
  37413. tN = e;
  37414. tD = c;
  37415. }
  37416. else {
  37417. sN = (b * e - c * d);
  37418. tN = (a * e - b * d);
  37419. if (sN < 0.0) {
  37420. sN = 0.0;
  37421. tN = e;
  37422. tD = c;
  37423. }
  37424. else if (sN > sD) {
  37425. sN = sD;
  37426. tN = e + b;
  37427. tD = c;
  37428. }
  37429. }
  37430. if (tN < 0.0) {
  37431. tN = 0.0;
  37432. // recompute sc for this edge
  37433. if (-d < 0.0) {
  37434. sN = 0.0;
  37435. }
  37436. else if (-d > a)
  37437. sN = sD;
  37438. else {
  37439. sN = -d;
  37440. sD = a;
  37441. }
  37442. }
  37443. else if (tN > tD) {
  37444. tN = tD;
  37445. // recompute sc for this edge
  37446. if ((-d + b) < 0.0) {
  37447. sN = 0;
  37448. }
  37449. else if ((-d + b) > a) {
  37450. sN = sD;
  37451. }
  37452. else {
  37453. sN = (-d + b);
  37454. sD = a;
  37455. }
  37456. }
  37457. // finally do the division to get sc and tc
  37458. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  37459. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  37460. // get the difference of the two closest points
  37461. var qtc = v.multiplyByFloats(tc, tc, tc);
  37462. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  37463. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  37464. if (isIntersected) {
  37465. return qtc.length();
  37466. }
  37467. return -1;
  37468. };
  37469. // Statics
  37470. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  37471. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  37472. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  37473. var direction = end.subtract(start);
  37474. direction.normalize();
  37475. return new Ray(start, direction);
  37476. };
  37477. /**
  37478. * 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
  37479. * transformed to the given world matrix.
  37480. * @param origin The origin point
  37481. * @param end The end point
  37482. * @param world a matrix to transform the ray to. Default is the identity matrix.
  37483. */
  37484. Ray.CreateNewFromTo = function (origin, end, world) {
  37485. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  37486. var direction = end.subtract(origin);
  37487. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  37488. direction.normalize();
  37489. return Ray.Transform(new Ray(origin, direction, length), world);
  37490. };
  37491. Ray.Transform = function (ray, matrix) {
  37492. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  37493. Ray.TransformToRef(ray, matrix, result);
  37494. return result;
  37495. };
  37496. Ray.TransformToRef = function (ray, matrix, result) {
  37497. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  37498. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  37499. result.length = ray.length;
  37500. var dir = result.direction;
  37501. var len = dir.length();
  37502. if (!(len === 0 || len === 1)) {
  37503. var num = 1.0 / len;
  37504. dir.x *= num;
  37505. dir.y *= num;
  37506. dir.z *= num;
  37507. result.length *= len;
  37508. }
  37509. };
  37510. return Ray;
  37511. }());
  37512. Ray.smallnum = 0.00000001;
  37513. Ray.rayl = 10e8;
  37514. BABYLON.Ray = Ray;
  37515. })(BABYLON || (BABYLON = {}));
  37516. //# sourceMappingURL=babylon.ray.js.map
  37517. var BABYLON;
  37518. (function (BABYLON) {
  37519. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  37520. if (boxMin.x > sphereCenter.x + sphereRadius)
  37521. return false;
  37522. if (sphereCenter.x - sphereRadius > boxMax.x)
  37523. return false;
  37524. if (boxMin.y > sphereCenter.y + sphereRadius)
  37525. return false;
  37526. if (sphereCenter.y - sphereRadius > boxMax.y)
  37527. return false;
  37528. if (boxMin.z > sphereCenter.z + sphereRadius)
  37529. return false;
  37530. if (sphereCenter.z - sphereRadius > boxMax.z)
  37531. return false;
  37532. return true;
  37533. };
  37534. var getLowestRoot = (function () {
  37535. var result = { root: 0, found: false };
  37536. return function (a, b, c, maxR) {
  37537. result.root = 0;
  37538. result.found = false;
  37539. var determinant = b * b - 4.0 * a * c;
  37540. if (determinant < 0)
  37541. return result;
  37542. var sqrtD = Math.sqrt(determinant);
  37543. var r1 = (-b - sqrtD) / (2.0 * a);
  37544. var r2 = (-b + sqrtD) / (2.0 * a);
  37545. if (r1 > r2) {
  37546. var temp = r2;
  37547. r2 = r1;
  37548. r1 = temp;
  37549. }
  37550. if (r1 > 0 && r1 < maxR) {
  37551. result.root = r1;
  37552. result.found = true;
  37553. return result;
  37554. }
  37555. if (r2 > 0 && r2 < maxR) {
  37556. result.root = r2;
  37557. result.found = true;
  37558. return result;
  37559. }
  37560. return result;
  37561. };
  37562. })();
  37563. var Collider = (function () {
  37564. function Collider() {
  37565. this.radius = BABYLON.Vector3.One();
  37566. this.retry = 0;
  37567. this.basePointWorld = BABYLON.Vector3.Zero();
  37568. this.velocityWorld = BABYLON.Vector3.Zero();
  37569. this.normalizedVelocity = BABYLON.Vector3.Zero();
  37570. this._collisionPoint = BABYLON.Vector3.Zero();
  37571. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  37572. this._tempVector = BABYLON.Vector3.Zero();
  37573. this._tempVector2 = BABYLON.Vector3.Zero();
  37574. this._tempVector3 = BABYLON.Vector3.Zero();
  37575. this._tempVector4 = BABYLON.Vector3.Zero();
  37576. this._edge = BABYLON.Vector3.Zero();
  37577. this._baseToVertex = BABYLON.Vector3.Zero();
  37578. this._destinationPoint = BABYLON.Vector3.Zero();
  37579. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  37580. this._displacementVector = BABYLON.Vector3.Zero();
  37581. this._collisionMask = -1;
  37582. }
  37583. Object.defineProperty(Collider.prototype, "collisionMask", {
  37584. get: function () {
  37585. return this._collisionMask;
  37586. },
  37587. set: function (mask) {
  37588. this._collisionMask = !isNaN(mask) ? mask : -1;
  37589. },
  37590. enumerable: true,
  37591. configurable: true
  37592. });
  37593. // Methods
  37594. Collider.prototype._initialize = function (source, dir, e) {
  37595. this.velocity = dir;
  37596. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  37597. this.basePoint = source;
  37598. source.multiplyToRef(this.radius, this.basePointWorld);
  37599. dir.multiplyToRef(this.radius, this.velocityWorld);
  37600. this.velocityWorldLength = this.velocityWorld.length();
  37601. this.epsilon = e;
  37602. this.collisionFound = false;
  37603. };
  37604. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  37605. pa.subtractToRef(point, this._tempVector);
  37606. pb.subtractToRef(point, this._tempVector2);
  37607. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  37608. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37609. if (d < 0)
  37610. return false;
  37611. pc.subtractToRef(point, this._tempVector3);
  37612. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  37613. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37614. if (d < 0)
  37615. return false;
  37616. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  37617. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37618. return d >= 0;
  37619. };
  37620. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  37621. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  37622. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  37623. if (distance > this.velocityWorldLength + max + sphereRadius) {
  37624. return false;
  37625. }
  37626. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  37627. return false;
  37628. return true;
  37629. };
  37630. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  37631. var t0;
  37632. var embeddedInPlane = false;
  37633. //defensive programming, actually not needed.
  37634. if (!trianglePlaneArray) {
  37635. trianglePlaneArray = [];
  37636. }
  37637. if (!trianglePlaneArray[faceIndex]) {
  37638. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  37639. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  37640. }
  37641. var trianglePlane = trianglePlaneArray[faceIndex];
  37642. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  37643. return;
  37644. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  37645. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  37646. if (normalDotVelocity == 0) {
  37647. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  37648. return;
  37649. embeddedInPlane = true;
  37650. t0 = 0;
  37651. }
  37652. else {
  37653. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  37654. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  37655. if (t0 > t1) {
  37656. var temp = t1;
  37657. t1 = t0;
  37658. t0 = temp;
  37659. }
  37660. if (t0 > 1.0 || t1 < 0.0)
  37661. return;
  37662. if (t0 < 0)
  37663. t0 = 0;
  37664. if (t0 > 1.0)
  37665. t0 = 1.0;
  37666. }
  37667. this._collisionPoint.copyFromFloats(0, 0, 0);
  37668. var found = false;
  37669. var t = 1.0;
  37670. if (!embeddedInPlane) {
  37671. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  37672. this.velocity.scaleToRef(t0, this._tempVector);
  37673. this._planeIntersectionPoint.addInPlace(this._tempVector);
  37674. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  37675. found = true;
  37676. t = t0;
  37677. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  37678. }
  37679. }
  37680. if (!found) {
  37681. var velocitySquaredLength = this.velocity.lengthSquared();
  37682. var a = velocitySquaredLength;
  37683. this.basePoint.subtractToRef(p1, this._tempVector);
  37684. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37685. var c = this._tempVector.lengthSquared() - 1.0;
  37686. var lowestRoot = getLowestRoot(a, b, c, t);
  37687. if (lowestRoot.found) {
  37688. t = lowestRoot.root;
  37689. found = true;
  37690. this._collisionPoint.copyFrom(p1);
  37691. }
  37692. this.basePoint.subtractToRef(p2, this._tempVector);
  37693. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37694. c = this._tempVector.lengthSquared() - 1.0;
  37695. lowestRoot = getLowestRoot(a, b, c, t);
  37696. if (lowestRoot.found) {
  37697. t = lowestRoot.root;
  37698. found = true;
  37699. this._collisionPoint.copyFrom(p2);
  37700. }
  37701. this.basePoint.subtractToRef(p3, this._tempVector);
  37702. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37703. c = this._tempVector.lengthSquared() - 1.0;
  37704. lowestRoot = getLowestRoot(a, b, c, t);
  37705. if (lowestRoot.found) {
  37706. t = lowestRoot.root;
  37707. found = true;
  37708. this._collisionPoint.copyFrom(p3);
  37709. }
  37710. p2.subtractToRef(p1, this._edge);
  37711. p1.subtractToRef(this.basePoint, this._baseToVertex);
  37712. var edgeSquaredLength = this._edge.lengthSquared();
  37713. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37714. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37715. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37716. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37717. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37718. lowestRoot = getLowestRoot(a, b, c, t);
  37719. if (lowestRoot.found) {
  37720. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37721. if (f >= 0.0 && f <= 1.0) {
  37722. t = lowestRoot.root;
  37723. found = true;
  37724. this._edge.scaleInPlace(f);
  37725. p1.addToRef(this._edge, this._collisionPoint);
  37726. }
  37727. }
  37728. p3.subtractToRef(p2, this._edge);
  37729. p2.subtractToRef(this.basePoint, this._baseToVertex);
  37730. edgeSquaredLength = this._edge.lengthSquared();
  37731. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37732. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37733. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37734. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37735. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37736. lowestRoot = getLowestRoot(a, b, c, t);
  37737. if (lowestRoot.found) {
  37738. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37739. if (f >= 0.0 && f <= 1.0) {
  37740. t = lowestRoot.root;
  37741. found = true;
  37742. this._edge.scaleInPlace(f);
  37743. p2.addToRef(this._edge, this._collisionPoint);
  37744. }
  37745. }
  37746. p1.subtractToRef(p3, this._edge);
  37747. p3.subtractToRef(this.basePoint, this._baseToVertex);
  37748. edgeSquaredLength = this._edge.lengthSquared();
  37749. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37750. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37751. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37752. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37753. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37754. lowestRoot = getLowestRoot(a, b, c, t);
  37755. if (lowestRoot.found) {
  37756. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37757. if (f >= 0.0 && f <= 1.0) {
  37758. t = lowestRoot.root;
  37759. found = true;
  37760. this._edge.scaleInPlace(f);
  37761. p3.addToRef(this._edge, this._collisionPoint);
  37762. }
  37763. }
  37764. }
  37765. if (found) {
  37766. var distToCollision = t * this.velocity.length();
  37767. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  37768. if (!this.intersectionPoint) {
  37769. this.intersectionPoint = this._collisionPoint.clone();
  37770. }
  37771. else {
  37772. this.intersectionPoint.copyFrom(this._collisionPoint);
  37773. }
  37774. this.nearestDistance = distToCollision;
  37775. this.collisionFound = true;
  37776. }
  37777. }
  37778. };
  37779. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  37780. for (var i = indexStart; i < indexEnd; i += 3) {
  37781. var p1 = pts[indices[i] - decal];
  37782. var p2 = pts[indices[i + 1] - decal];
  37783. var p3 = pts[indices[i + 2] - decal];
  37784. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  37785. }
  37786. };
  37787. Collider.prototype._getResponse = function (pos, vel) {
  37788. pos.addToRef(vel, this._destinationPoint);
  37789. vel.scaleInPlace((this.nearestDistance / vel.length()));
  37790. this.basePoint.addToRef(vel, pos);
  37791. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  37792. this._slidePlaneNormal.normalize();
  37793. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  37794. pos.addInPlace(this._displacementVector);
  37795. this.intersectionPoint.addInPlace(this._displacementVector);
  37796. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  37797. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  37798. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  37799. };
  37800. return Collider;
  37801. }());
  37802. BABYLON.Collider = Collider;
  37803. })(BABYLON || (BABYLON = {}));
  37804. //# sourceMappingURL=babylon.collider.js.map
  37805. var BABYLON;
  37806. (function (BABYLON) {
  37807. //WebWorker code will be inserted to this variable.
  37808. BABYLON.CollisionWorker = "";
  37809. var WorkerTaskType;
  37810. (function (WorkerTaskType) {
  37811. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  37812. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  37813. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  37814. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  37815. var WorkerReplyType;
  37816. (function (WorkerReplyType) {
  37817. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  37818. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  37819. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  37820. var CollisionCoordinatorWorker = (function () {
  37821. function CollisionCoordinatorWorker() {
  37822. var _this = this;
  37823. this._scaledPosition = BABYLON.Vector3.Zero();
  37824. this._scaledVelocity = BABYLON.Vector3.Zero();
  37825. this.onMeshUpdated = function (mesh) {
  37826. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  37827. };
  37828. this.onGeometryUpdated = function (geometry) {
  37829. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  37830. };
  37831. this._afterRender = function () {
  37832. if (!_this._init)
  37833. return;
  37834. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  37835. return;
  37836. }
  37837. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  37838. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  37839. if (_this._runningUpdated > 4) {
  37840. return;
  37841. }
  37842. ++_this._runningUpdated;
  37843. var payload = {
  37844. updatedMeshes: _this._addUpdateMeshesList,
  37845. updatedGeometries: _this._addUpdateGeometriesList,
  37846. removedGeometries: _this._toRemoveGeometryArray,
  37847. removedMeshes: _this._toRemoveMeshesArray
  37848. };
  37849. var message = {
  37850. payload: payload,
  37851. taskType: WorkerTaskType.UPDATE
  37852. };
  37853. var serializable = [];
  37854. for (var id in payload.updatedGeometries) {
  37855. if (payload.updatedGeometries.hasOwnProperty(id)) {
  37856. //prepare transferables
  37857. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  37858. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  37859. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  37860. }
  37861. }
  37862. _this._worker.postMessage(message, serializable);
  37863. _this._addUpdateMeshesList = {};
  37864. _this._addUpdateGeometriesList = {};
  37865. _this._toRemoveGeometryArray = [];
  37866. _this._toRemoveMeshesArray = [];
  37867. };
  37868. this._onMessageFromWorker = function (e) {
  37869. var returnData = e.data;
  37870. if (returnData.error != WorkerReplyType.SUCCESS) {
  37871. //TODO what errors can be returned from the worker?
  37872. BABYLON.Tools.Warn("error returned from worker!");
  37873. return;
  37874. }
  37875. switch (returnData.taskType) {
  37876. case WorkerTaskType.INIT:
  37877. _this._init = true;
  37878. //Update the worked with ALL of the scene's current state
  37879. _this._scene.meshes.forEach(function (mesh) {
  37880. _this.onMeshAdded(mesh);
  37881. });
  37882. _this._scene.getGeometries().forEach(function (geometry) {
  37883. _this.onGeometryAdded(geometry);
  37884. });
  37885. break;
  37886. case WorkerTaskType.UPDATE:
  37887. _this._runningUpdated--;
  37888. break;
  37889. case WorkerTaskType.COLLIDE:
  37890. _this._runningCollisionTask = false;
  37891. var returnPayload = returnData.payload;
  37892. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  37893. return;
  37894. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  37895. //cleanup
  37896. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  37897. break;
  37898. }
  37899. };
  37900. this._collisionsCallbackArray = [];
  37901. this._init = false;
  37902. this._runningUpdated = 0;
  37903. this._runningCollisionTask = false;
  37904. this._addUpdateMeshesList = {};
  37905. this._addUpdateGeometriesList = {};
  37906. this._toRemoveGeometryArray = [];
  37907. this._toRemoveMeshesArray = [];
  37908. }
  37909. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  37910. if (!this._init)
  37911. return;
  37912. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  37913. return;
  37914. position.divideToRef(collider.radius, this._scaledPosition);
  37915. velocity.divideToRef(collider.radius, this._scaledVelocity);
  37916. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  37917. var payload = {
  37918. collider: {
  37919. position: this._scaledPosition.asArray(),
  37920. velocity: this._scaledVelocity.asArray(),
  37921. radius: collider.radius.asArray()
  37922. },
  37923. collisionId: collisionIndex,
  37924. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  37925. maximumRetry: maximumRetry
  37926. };
  37927. var message = {
  37928. payload: payload,
  37929. taskType: WorkerTaskType.COLLIDE
  37930. };
  37931. this._worker.postMessage(message);
  37932. };
  37933. CollisionCoordinatorWorker.prototype.init = function (scene) {
  37934. this._scene = scene;
  37935. this._scene.registerAfterRender(this._afterRender);
  37936. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  37937. this._worker = new Worker(workerUrl);
  37938. this._worker.onmessage = this._onMessageFromWorker;
  37939. var message = {
  37940. payload: {},
  37941. taskType: WorkerTaskType.INIT
  37942. };
  37943. this._worker.postMessage(message);
  37944. };
  37945. CollisionCoordinatorWorker.prototype.destroy = function () {
  37946. this._scene.unregisterAfterRender(this._afterRender);
  37947. this._worker.terminate();
  37948. };
  37949. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  37950. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  37951. this.onMeshUpdated(mesh);
  37952. };
  37953. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  37954. this._toRemoveMeshesArray.push(mesh.uniqueId);
  37955. };
  37956. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  37957. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  37958. geometry.onGeometryUpdated = this.onGeometryUpdated;
  37959. this.onGeometryUpdated(geometry);
  37960. };
  37961. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  37962. this._toRemoveGeometryArray.push(geometry.id);
  37963. };
  37964. return CollisionCoordinatorWorker;
  37965. }());
  37966. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  37967. var submeshes = [];
  37968. if (mesh.subMeshes) {
  37969. submeshes = mesh.subMeshes.map(function (sm, idx) {
  37970. return {
  37971. position: idx,
  37972. verticesStart: sm.verticesStart,
  37973. verticesCount: sm.verticesCount,
  37974. indexStart: sm.indexStart,
  37975. indexCount: sm.indexCount,
  37976. hasMaterial: !!sm.getMaterial(),
  37977. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  37978. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  37979. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  37980. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  37981. };
  37982. });
  37983. }
  37984. var geometryId = null;
  37985. if (mesh instanceof BABYLON.Mesh) {
  37986. geometryId = mesh.geometry ? mesh.geometry.id : null;
  37987. }
  37988. else if (mesh instanceof BABYLON.InstancedMesh) {
  37989. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  37990. }
  37991. return {
  37992. uniqueId: mesh.uniqueId,
  37993. id: mesh.id,
  37994. name: mesh.name,
  37995. geometryId: geometryId,
  37996. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  37997. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  37998. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  37999. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  38000. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  38001. subMeshes: submeshes,
  38002. checkCollisions: mesh.checkCollisions
  38003. };
  38004. };
  38005. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  38006. return {
  38007. id: geometry.id,
  38008. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  38009. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  38010. indices: new Uint32Array(geometry.getIndices() || []),
  38011. };
  38012. };
  38013. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  38014. var CollisionCoordinatorLegacy = (function () {
  38015. function CollisionCoordinatorLegacy() {
  38016. this._scaledPosition = BABYLON.Vector3.Zero();
  38017. this._scaledVelocity = BABYLON.Vector3.Zero();
  38018. this._finalPosition = BABYLON.Vector3.Zero();
  38019. }
  38020. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  38021. position.divideToRef(collider.radius, this._scaledPosition);
  38022. velocity.divideToRef(collider.radius, this._scaledVelocity);
  38023. collider.collidedMesh = null;
  38024. collider.retry = 0;
  38025. collider.initialVelocity = this._scaledVelocity;
  38026. collider.initialPosition = this._scaledPosition;
  38027. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  38028. this._finalPosition.multiplyInPlace(collider.radius);
  38029. //run the callback
  38030. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  38031. };
  38032. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  38033. this._scene = scene;
  38034. };
  38035. CollisionCoordinatorLegacy.prototype.destroy = function () {
  38036. //Legacy need no destruction method.
  38037. };
  38038. //No update in legacy mode
  38039. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  38040. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  38041. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  38042. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  38043. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  38044. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  38045. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  38046. if (excludedMesh === void 0) { excludedMesh = null; }
  38047. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  38048. if (collider.retry >= maximumRetry) {
  38049. finalPosition.copyFrom(position);
  38050. return;
  38051. }
  38052. // Check if this is a mesh else camera or -1
  38053. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  38054. collider._initialize(position, velocity, closeDistance);
  38055. // Check all meshes
  38056. for (var index = 0; index < this._scene.meshes.length; index++) {
  38057. var mesh = this._scene.meshes[index];
  38058. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  38059. mesh._checkCollision(collider);
  38060. }
  38061. }
  38062. if (!collider.collisionFound) {
  38063. position.addToRef(velocity, finalPosition);
  38064. return;
  38065. }
  38066. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  38067. collider._getResponse(position, velocity);
  38068. }
  38069. if (velocity.length() <= closeDistance) {
  38070. finalPosition.copyFrom(position);
  38071. return;
  38072. }
  38073. collider.retry++;
  38074. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  38075. };
  38076. return CollisionCoordinatorLegacy;
  38077. }());
  38078. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  38079. })(BABYLON || (BABYLON = {}));
  38080. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  38081. var BABYLON;
  38082. (function (BABYLON) {
  38083. var Particle = (function () {
  38084. function Particle() {
  38085. this.position = BABYLON.Vector3.Zero();
  38086. this.direction = BABYLON.Vector3.Zero();
  38087. this.color = new BABYLON.Color4(0, 0, 0, 0);
  38088. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  38089. this.lifeTime = 1.0;
  38090. this.age = 0;
  38091. this.size = 0;
  38092. this.angle = 0;
  38093. this.angularSpeed = 0;
  38094. }
  38095. Particle.prototype.copyTo = function (other) {
  38096. other.position.copyFrom(this.position);
  38097. other.direction.copyFrom(this.direction);
  38098. other.color.copyFrom(this.color);
  38099. other.colorStep.copyFrom(this.colorStep);
  38100. other.lifeTime = this.lifeTime;
  38101. other.age = this.age;
  38102. other.size = this.size;
  38103. other.angle = this.angle;
  38104. other.angularSpeed = this.angularSpeed;
  38105. };
  38106. return Particle;
  38107. }());
  38108. BABYLON.Particle = Particle;
  38109. })(BABYLON || (BABYLON = {}));
  38110. //# sourceMappingURL=babylon.particle.js.map
  38111. var BABYLON;
  38112. (function (BABYLON) {
  38113. var randomNumber = function (min, max) {
  38114. if (min === max) {
  38115. return (min);
  38116. }
  38117. var random = Math.random();
  38118. return ((random * (max - min)) + min);
  38119. };
  38120. var ParticleSystem = (function () {
  38121. function ParticleSystem(name, capacity, scene, customEffect) {
  38122. var _this = this;
  38123. this.name = name;
  38124. // Members
  38125. this.animations = [];
  38126. this.renderingGroupId = 0;
  38127. this.emitter = null;
  38128. this.emitRate = 10;
  38129. this.manualEmitCount = -1;
  38130. this.updateSpeed = 0.01;
  38131. this.targetStopDuration = 0;
  38132. this.disposeOnStop = false;
  38133. this.minEmitPower = 1;
  38134. this.maxEmitPower = 1;
  38135. this.minLifeTime = 1;
  38136. this.maxLifeTime = 1;
  38137. this.minSize = 1;
  38138. this.maxSize = 1;
  38139. this.minAngularSpeed = 0;
  38140. this.maxAngularSpeed = 0;
  38141. this.layerMask = 0x0FFFFFFF;
  38142. this.customShader = null;
  38143. this.preventAutoStart = false;
  38144. /**
  38145. * An event triggered when the system is disposed.
  38146. * @type {BABYLON.Observable}
  38147. */
  38148. this.onDisposeObservable = new BABYLON.Observable();
  38149. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  38150. this.forceDepthWrite = false;
  38151. this.gravity = BABYLON.Vector3.Zero();
  38152. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  38153. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  38154. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  38155. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38156. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  38157. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  38158. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  38159. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  38160. this.particles = new Array();
  38161. this._stockParticles = new Array();
  38162. this._newPartsExcess = 0;
  38163. this._vertexBuffers = {};
  38164. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  38165. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  38166. this._scaledDirection = BABYLON.Vector3.Zero();
  38167. this._scaledGravity = BABYLON.Vector3.Zero();
  38168. this._currentRenderId = -1;
  38169. this._started = false;
  38170. this._stopped = false;
  38171. this._actualFrame = 0;
  38172. this.id = name;
  38173. this._capacity = capacity;
  38174. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  38175. this._customEffect = customEffect;
  38176. scene.particleSystems.push(this);
  38177. var indices = [];
  38178. var index = 0;
  38179. for (var count = 0; count < capacity; count++) {
  38180. indices.push(index);
  38181. indices.push(index + 1);
  38182. indices.push(index + 2);
  38183. indices.push(index);
  38184. indices.push(index + 2);
  38185. indices.push(index + 3);
  38186. index += 4;
  38187. }
  38188. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38189. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  38190. this._vertexData = new Float32Array(capacity * 11 * 4);
  38191. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  38192. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  38193. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  38194. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  38195. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  38196. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  38197. this._vertexBuffers["options"] = options;
  38198. // Default behaviors
  38199. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  38200. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  38201. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  38202. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  38203. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  38204. };
  38205. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  38206. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  38207. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  38208. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  38209. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  38210. };
  38211. this.updateFunction = function (particles) {
  38212. for (var index = 0; index < particles.length; index++) {
  38213. var particle = particles[index];
  38214. particle.age += _this._scaledUpdateSpeed;
  38215. if (particle.age >= particle.lifeTime) {
  38216. _this.recycleParticle(particle);
  38217. index--;
  38218. continue;
  38219. }
  38220. else {
  38221. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  38222. particle.color.addInPlace(_this._scaledColorStep);
  38223. if (particle.color.a < 0)
  38224. particle.color.a = 0;
  38225. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  38226. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  38227. particle.position.addInPlace(_this._scaledDirection);
  38228. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  38229. particle.direction.addInPlace(_this._scaledGravity);
  38230. }
  38231. }
  38232. };
  38233. }
  38234. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  38235. set: function (callback) {
  38236. if (this._onDisposeObserver) {
  38237. this.onDisposeObservable.remove(this._onDisposeObserver);
  38238. }
  38239. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  38240. },
  38241. enumerable: true,
  38242. configurable: true
  38243. });
  38244. ParticleSystem.prototype.recycleParticle = function (particle) {
  38245. var lastParticle = this.particles.pop();
  38246. if (lastParticle !== particle) {
  38247. lastParticle.copyTo(particle);
  38248. this._stockParticles.push(lastParticle);
  38249. }
  38250. };
  38251. ParticleSystem.prototype.getCapacity = function () {
  38252. return this._capacity;
  38253. };
  38254. ParticleSystem.prototype.isAlive = function () {
  38255. return this._alive;
  38256. };
  38257. ParticleSystem.prototype.isStarted = function () {
  38258. return this._started;
  38259. };
  38260. ParticleSystem.prototype.start = function () {
  38261. this._started = true;
  38262. this._stopped = false;
  38263. this._actualFrame = 0;
  38264. };
  38265. ParticleSystem.prototype.stop = function () {
  38266. this._stopped = true;
  38267. };
  38268. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  38269. var offset = index * 11;
  38270. this._vertexData[offset] = particle.position.x;
  38271. this._vertexData[offset + 1] = particle.position.y;
  38272. this._vertexData[offset + 2] = particle.position.z;
  38273. this._vertexData[offset + 3] = particle.color.r;
  38274. this._vertexData[offset + 4] = particle.color.g;
  38275. this._vertexData[offset + 5] = particle.color.b;
  38276. this._vertexData[offset + 6] = particle.color.a;
  38277. this._vertexData[offset + 7] = particle.angle;
  38278. this._vertexData[offset + 8] = particle.size;
  38279. this._vertexData[offset + 9] = offsetX;
  38280. this._vertexData[offset + 10] = offsetY;
  38281. };
  38282. ParticleSystem.prototype._update = function (newParticles) {
  38283. // Update current
  38284. this._alive = this.particles.length > 0;
  38285. this.updateFunction(this.particles);
  38286. // Add new ones
  38287. var worldMatrix;
  38288. if (this.emitter.position) {
  38289. worldMatrix = this.emitter.getWorldMatrix();
  38290. }
  38291. else {
  38292. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  38293. }
  38294. var particle;
  38295. for (var index = 0; index < newParticles; index++) {
  38296. if (this.particles.length === this._capacity) {
  38297. break;
  38298. }
  38299. if (this._stockParticles.length !== 0) {
  38300. particle = this._stockParticles.pop();
  38301. particle.age = 0;
  38302. }
  38303. else {
  38304. particle = new BABYLON.Particle();
  38305. }
  38306. this.particles.push(particle);
  38307. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  38308. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  38309. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  38310. particle.size = randomNumber(this.minSize, this.maxSize);
  38311. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  38312. this.startPositionFunction(worldMatrix, particle.position, particle);
  38313. var step = randomNumber(0, 1.0);
  38314. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  38315. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  38316. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  38317. }
  38318. };
  38319. ParticleSystem.prototype._getEffect = function () {
  38320. if (this._customEffect) {
  38321. return this._customEffect;
  38322. }
  38323. ;
  38324. var defines = [];
  38325. if (this._scene.clipPlane) {
  38326. defines.push("#define CLIPPLANE");
  38327. }
  38328. // Effect
  38329. var join = defines.join("\n");
  38330. if (this._cachedDefines !== join) {
  38331. this._cachedDefines = join;
  38332. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  38333. }
  38334. return this._effect;
  38335. };
  38336. ParticleSystem.prototype.animate = function () {
  38337. if (!this._started)
  38338. return;
  38339. var effect = this._getEffect();
  38340. // Check
  38341. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  38342. return;
  38343. if (this._currentRenderId === this._scene.getRenderId()) {
  38344. return;
  38345. }
  38346. this._currentRenderId = this._scene.getRenderId();
  38347. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  38348. // determine the number of particles we need to create
  38349. var newParticles;
  38350. if (this.manualEmitCount > -1) {
  38351. newParticles = this.manualEmitCount;
  38352. this._newPartsExcess = 0;
  38353. this.manualEmitCount = 0;
  38354. }
  38355. else {
  38356. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  38357. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  38358. }
  38359. if (this._newPartsExcess > 1.0) {
  38360. newParticles += this._newPartsExcess >> 0;
  38361. this._newPartsExcess -= this._newPartsExcess >> 0;
  38362. }
  38363. this._alive = false;
  38364. if (!this._stopped) {
  38365. this._actualFrame += this._scaledUpdateSpeed;
  38366. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  38367. this.stop();
  38368. }
  38369. else {
  38370. newParticles = 0;
  38371. }
  38372. this._update(newParticles);
  38373. // Stopped?
  38374. if (this._stopped) {
  38375. if (!this._alive) {
  38376. this._started = false;
  38377. if (this.disposeOnStop) {
  38378. this._scene._toBeDisposed.push(this);
  38379. }
  38380. }
  38381. }
  38382. // Update VBO
  38383. var offset = 0;
  38384. for (var index = 0; index < this.particles.length; index++) {
  38385. var particle = this.particles[index];
  38386. this._appendParticleVertex(offset++, particle, 0, 0);
  38387. this._appendParticleVertex(offset++, particle, 1, 0);
  38388. this._appendParticleVertex(offset++, particle, 1, 1);
  38389. this._appendParticleVertex(offset++, particle, 0, 1);
  38390. }
  38391. this._vertexBuffer.update(this._vertexData);
  38392. };
  38393. ParticleSystem.prototype.render = function () {
  38394. var effect = this._getEffect();
  38395. // Check
  38396. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  38397. return 0;
  38398. var engine = this._scene.getEngine();
  38399. // Render
  38400. engine.enableEffect(effect);
  38401. engine.setState(false);
  38402. var viewMatrix = this._scene.getViewMatrix();
  38403. effect.setTexture("diffuseSampler", this.particleTexture);
  38404. effect.setMatrix("view", viewMatrix);
  38405. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  38406. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  38407. if (this._scene.clipPlane) {
  38408. var clipPlane = this._scene.clipPlane;
  38409. var invView = viewMatrix.clone();
  38410. invView.invert();
  38411. effect.setMatrix("invView", invView);
  38412. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38413. }
  38414. // VBOs
  38415. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  38416. // Draw order
  38417. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  38418. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  38419. }
  38420. else {
  38421. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38422. }
  38423. if (this.forceDepthWrite) {
  38424. engine.setDepthWrite(true);
  38425. }
  38426. engine.draw(true, 0, this.particles.length * 6);
  38427. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38428. return this.particles.length;
  38429. };
  38430. ParticleSystem.prototype.dispose = function () {
  38431. if (this._vertexBuffer) {
  38432. this._vertexBuffer.dispose();
  38433. this._vertexBuffer = null;
  38434. }
  38435. if (this._indexBuffer) {
  38436. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38437. this._indexBuffer = null;
  38438. }
  38439. if (this.particleTexture) {
  38440. this.particleTexture.dispose();
  38441. this.particleTexture = null;
  38442. }
  38443. // Remove from scene
  38444. var index = this._scene.particleSystems.indexOf(this);
  38445. this._scene.particleSystems.splice(index, 1);
  38446. // Callback
  38447. this.onDisposeObservable.notifyObservers(this);
  38448. this.onDisposeObservable.clear();
  38449. };
  38450. // Clone
  38451. ParticleSystem.prototype.clone = function (name, newEmitter) {
  38452. var custom = null;
  38453. var program = null;
  38454. if (this.customShader != null) {
  38455. program = this.customShader;
  38456. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  38457. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  38458. }
  38459. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  38460. result.customShader = program;
  38461. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  38462. if (newEmitter === undefined) {
  38463. newEmitter = this.emitter;
  38464. }
  38465. result.emitter = newEmitter;
  38466. if (this.particleTexture) {
  38467. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  38468. }
  38469. if (!this.preventAutoStart) {
  38470. result.start();
  38471. }
  38472. return result;
  38473. };
  38474. ParticleSystem.prototype.serialize = function () {
  38475. var serializationObject = {};
  38476. serializationObject.name = this.name;
  38477. serializationObject.id = this.id;
  38478. // Emitter
  38479. if (this.emitter.position) {
  38480. serializationObject.emitterId = this.emitter.id;
  38481. }
  38482. else {
  38483. serializationObject.emitter = this.emitter.asArray();
  38484. }
  38485. serializationObject.capacity = this.getCapacity();
  38486. if (this.particleTexture) {
  38487. serializationObject.textureName = this.particleTexture.name;
  38488. }
  38489. // Animations
  38490. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  38491. // Particle system
  38492. serializationObject.minAngularSpeed = this.minAngularSpeed;
  38493. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  38494. serializationObject.minSize = this.minSize;
  38495. serializationObject.maxSize = this.maxSize;
  38496. serializationObject.minEmitPower = this.minEmitPower;
  38497. serializationObject.maxEmitPower = this.maxEmitPower;
  38498. serializationObject.minLifeTime = this.minLifeTime;
  38499. serializationObject.maxLifeTime = this.maxLifeTime;
  38500. serializationObject.emitRate = this.emitRate;
  38501. serializationObject.minEmitBox = this.minEmitBox.asArray();
  38502. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  38503. serializationObject.gravity = this.gravity.asArray();
  38504. serializationObject.direction1 = this.direction1.asArray();
  38505. serializationObject.direction2 = this.direction2.asArray();
  38506. serializationObject.color1 = this.color1.asArray();
  38507. serializationObject.color2 = this.color2.asArray();
  38508. serializationObject.colorDead = this.colorDead.asArray();
  38509. serializationObject.updateSpeed = this.updateSpeed;
  38510. serializationObject.targetStopDuration = this.targetStopDuration;
  38511. serializationObject.textureMask = this.textureMask.asArray();
  38512. serializationObject.blendMode = this.blendMode;
  38513. serializationObject.customShader = this.customShader;
  38514. serializationObject.preventAutoStart = this.preventAutoStart;
  38515. return serializationObject;
  38516. };
  38517. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  38518. var name = parsedParticleSystem.name;
  38519. var custom = null;
  38520. var program = null;
  38521. if (parsedParticleSystem.customShader) {
  38522. program = parsedParticleSystem.customShader;
  38523. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  38524. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  38525. }
  38526. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  38527. particleSystem.customShader = program;
  38528. if (parsedParticleSystem.id) {
  38529. particleSystem.id = parsedParticleSystem.id;
  38530. }
  38531. // Auto start
  38532. if (parsedParticleSystem.preventAutoStart) {
  38533. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  38534. }
  38535. // Texture
  38536. if (parsedParticleSystem.textureName) {
  38537. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  38538. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  38539. }
  38540. // Emitter
  38541. if (parsedParticleSystem.emitterId) {
  38542. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  38543. }
  38544. else {
  38545. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  38546. }
  38547. // Animations
  38548. if (parsedParticleSystem.animations) {
  38549. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  38550. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  38551. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  38552. }
  38553. }
  38554. if (parsedParticleSystem.autoAnimate) {
  38555. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  38556. }
  38557. // Particle system
  38558. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  38559. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  38560. particleSystem.minSize = parsedParticleSystem.minSize;
  38561. particleSystem.maxSize = parsedParticleSystem.maxSize;
  38562. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  38563. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  38564. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  38565. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  38566. particleSystem.emitRate = parsedParticleSystem.emitRate;
  38567. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  38568. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  38569. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  38570. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  38571. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  38572. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  38573. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  38574. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  38575. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  38576. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  38577. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  38578. particleSystem.blendMode = parsedParticleSystem.blendMode;
  38579. if (!particleSystem.preventAutoStart) {
  38580. particleSystem.start();
  38581. }
  38582. return particleSystem;
  38583. };
  38584. return ParticleSystem;
  38585. }());
  38586. // Statics
  38587. ParticleSystem.BLENDMODE_ONEONE = 0;
  38588. ParticleSystem.BLENDMODE_STANDARD = 1;
  38589. BABYLON.ParticleSystem = ParticleSystem;
  38590. })(BABYLON || (BABYLON = {}));
  38591. //# sourceMappingURL=babylon.particleSystem.js.map
  38592. var BABYLON;
  38593. (function (BABYLON) {
  38594. var SolidParticle = (function () {
  38595. /**
  38596. * Creates a Solid Particle object.
  38597. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  38598. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  38599. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  38600. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  38601. * `shapeId` (integer) is the model shape identifier in the SPS.
  38602. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  38603. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  38604. */
  38605. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  38606. this.idx = 0; // particle global index
  38607. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  38608. this.position = BABYLON.Vector3.Zero(); // position
  38609. this.rotation = BABYLON.Vector3.Zero(); // rotation
  38610. this.scaling = BABYLON.Vector3.One(); // scaling
  38611. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  38612. this.velocity = BABYLON.Vector3.Zero(); // velocity
  38613. this.alive = true; // alive
  38614. this.isVisible = true; // visibility
  38615. this._pos = 0; // index of this particle in the global "positions" array
  38616. this.shapeId = 0; // model shape id
  38617. this.idxInShape = 0; // index of the particle in its shape id
  38618. this.idx = particleIndex;
  38619. this._pos = positionIndex;
  38620. this._model = model;
  38621. this.shapeId = shapeId;
  38622. this.idxInShape = idxInShape;
  38623. this._sps = sps;
  38624. if (modelBoundingInfo) {
  38625. this._modelBoundingInfo = modelBoundingInfo;
  38626. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  38627. }
  38628. }
  38629. Object.defineProperty(SolidParticle.prototype, "scale", {
  38630. /**
  38631. * legacy support, changed scale to scaling
  38632. */
  38633. get: function () {
  38634. return this.scaling;
  38635. },
  38636. set: function (scale) {
  38637. this.scaling = scale;
  38638. },
  38639. enumerable: true,
  38640. configurable: true
  38641. });
  38642. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  38643. /**
  38644. * legacy support, changed quaternion to rotationQuaternion
  38645. */
  38646. get: function () {
  38647. return this.rotationQuaternion;
  38648. },
  38649. set: function (q) {
  38650. this.rotationQuaternion = q;
  38651. },
  38652. enumerable: true,
  38653. configurable: true
  38654. });
  38655. /**
  38656. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  38657. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  38658. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  38659. */
  38660. SolidParticle.prototype.intersectsMesh = function (target) {
  38661. if (!this._boundingInfo || !target._boundingInfo) {
  38662. return false;
  38663. }
  38664. if (this._sps._bSphereOnly) {
  38665. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  38666. }
  38667. return this._boundingInfo.intersects(target._boundingInfo, false);
  38668. };
  38669. return SolidParticle;
  38670. }());
  38671. BABYLON.SolidParticle = SolidParticle;
  38672. var ModelShape = (function () {
  38673. /**
  38674. * 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.
  38675. * SPS internal tool, don't use it manually.
  38676. */
  38677. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  38678. this.shapeID = id;
  38679. this._shape = shape;
  38680. this._shapeUV = shapeUV;
  38681. this._positionFunction = posFunction;
  38682. this._vertexFunction = vtxFunction;
  38683. }
  38684. return ModelShape;
  38685. }());
  38686. BABYLON.ModelShape = ModelShape;
  38687. })(BABYLON || (BABYLON = {}));
  38688. //# sourceMappingURL=babylon.solidParticle.js.map
  38689. var BABYLON;
  38690. (function (BABYLON) {
  38691. /**
  38692. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  38693. */
  38694. var SolidParticleSystem = (function () {
  38695. /**
  38696. * Creates a SPS (Solid Particle System) object.
  38697. * `name` (String) is the SPS name, this will be the underlying mesh name.
  38698. * `scene` (Scene) is the scene in which the SPS is added.
  38699. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  38700. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  38701. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  38702. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  38703. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  38704. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  38705. */
  38706. function SolidParticleSystem(name, scene, options) {
  38707. // public members
  38708. /**
  38709. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  38710. * Example : var p = SPS.particles[i];
  38711. */
  38712. this.particles = new Array();
  38713. /**
  38714. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  38715. */
  38716. this.nbParticles = 0;
  38717. /**
  38718. * If the particles must ever face the camera (default false). Useful for planar particles.
  38719. */
  38720. this.billboard = false;
  38721. /**
  38722. * Recompute normals when adding a shape
  38723. */
  38724. this.recomputeNormals = true;
  38725. /**
  38726. * This a counter ofr your own usage. It's not set by any SPS functions.
  38727. */
  38728. this.counter = 0;
  38729. /**
  38730. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  38731. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  38732. */
  38733. this.vars = {};
  38734. this._positions = new Array();
  38735. this._indices = new Array();
  38736. this._normals = new Array();
  38737. this._colors = new Array();
  38738. this._uvs = new Array();
  38739. this._index = 0; // indices index
  38740. this._updatable = true;
  38741. this._pickable = false;
  38742. this._isVisibilityBoxLocked = false;
  38743. this._alwaysVisible = false;
  38744. this._shapeCounter = 0;
  38745. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  38746. this._color = new BABYLON.Color4(0, 0, 0, 0);
  38747. this._computeParticleColor = true;
  38748. this._computeParticleTexture = true;
  38749. this._computeParticleRotation = true;
  38750. this._computeParticleVertex = false;
  38751. this._computeBoundingBox = false;
  38752. this._cam_axisZ = BABYLON.Vector3.Zero();
  38753. this._cam_axisY = BABYLON.Vector3.Zero();
  38754. this._cam_axisX = BABYLON.Vector3.Zero();
  38755. this._axisX = BABYLON.Axis.X;
  38756. this._axisY = BABYLON.Axis.Y;
  38757. this._axisZ = BABYLON.Axis.Z;
  38758. this._camDir = BABYLON.Vector3.Zero();
  38759. this._rotMatrix = new BABYLON.Matrix();
  38760. this._invertMatrix = new BABYLON.Matrix();
  38761. this._rotated = BABYLON.Vector3.Zero();
  38762. this._quaternion = new BABYLON.Quaternion();
  38763. this._vertex = BABYLON.Vector3.Zero();
  38764. this._normal = BABYLON.Vector3.Zero();
  38765. this._yaw = 0.0;
  38766. this._pitch = 0.0;
  38767. this._roll = 0.0;
  38768. this._halfroll = 0.0;
  38769. this._halfpitch = 0.0;
  38770. this._halfyaw = 0.0;
  38771. this._sinRoll = 0.0;
  38772. this._cosRoll = 0.0;
  38773. this._sinPitch = 0.0;
  38774. this._cosPitch = 0.0;
  38775. this._sinYaw = 0.0;
  38776. this._cosYaw = 0.0;
  38777. this._w = 0.0;
  38778. this._mustUnrotateFixedNormals = false;
  38779. this._minimum = BABYLON.Tmp.Vector3[0];
  38780. this._maximum = BABYLON.Tmp.Vector3[1];
  38781. this._scale = BABYLON.Tmp.Vector3[2];
  38782. this._translation = BABYLON.Tmp.Vector3[3];
  38783. this._minBbox = BABYLON.Tmp.Vector3[4];
  38784. this._maxBbox = BABYLON.Tmp.Vector3[5];
  38785. this._particlesIntersect = false;
  38786. this._bSphereOnly = false;
  38787. this._bSphereRadiusFactor = 1.0;
  38788. this.name = name;
  38789. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  38790. this._camera = scene.activeCamera;
  38791. this._pickable = options ? options.isPickable : false;
  38792. this._particlesIntersect = options ? options.particleIntersection : false;
  38793. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  38794. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  38795. if (options && options.updatable) {
  38796. this._updatable = options.updatable;
  38797. }
  38798. else {
  38799. this._updatable = true;
  38800. }
  38801. if (this._pickable) {
  38802. this.pickedParticles = [];
  38803. }
  38804. }
  38805. /**
  38806. * Builds the SPS underlying mesh. Returns a standard Mesh.
  38807. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  38808. */
  38809. SolidParticleSystem.prototype.buildMesh = function () {
  38810. if (this.nbParticles === 0) {
  38811. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  38812. this.addShape(triangle, 1);
  38813. triangle.dispose();
  38814. }
  38815. this._positions32 = new Float32Array(this._positions);
  38816. this._uvs32 = new Float32Array(this._uvs);
  38817. this._colors32 = new Float32Array(this._colors);
  38818. if (this.recomputeNormals) {
  38819. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  38820. }
  38821. this._normals32 = new Float32Array(this._normals);
  38822. this._fixedNormal32 = new Float32Array(this._normals);
  38823. if (this._mustUnrotateFixedNormals) {
  38824. this._unrotateFixedNormals();
  38825. }
  38826. var vertexData = new BABYLON.VertexData();
  38827. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  38828. vertexData.indices = this._indices;
  38829. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  38830. if (this._uvs32) {
  38831. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  38832. ;
  38833. }
  38834. if (this._colors32) {
  38835. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  38836. }
  38837. var mesh = new BABYLON.Mesh(this.name, this._scene);
  38838. vertexData.applyToMesh(mesh, this._updatable);
  38839. this.mesh = mesh;
  38840. this.mesh.isPickable = this._pickable;
  38841. // free memory
  38842. this._positions = null;
  38843. this._normals = null;
  38844. this._uvs = null;
  38845. this._colors = null;
  38846. if (!this._updatable) {
  38847. this.particles.length = 0;
  38848. }
  38849. return mesh;
  38850. };
  38851. /**
  38852. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  38853. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  38854. * Thus the particles generated from `digest()` have their property `position` set yet.
  38855. * `mesh` ( Mesh ) is the mesh to be digested
  38856. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  38857. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  38858. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  38859. */
  38860. SolidParticleSystem.prototype.digest = function (mesh, options) {
  38861. var size = (options && options.facetNb) || 1;
  38862. var number = (options && options.number);
  38863. var delta = (options && options.delta) || 0;
  38864. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38865. var meshInd = mesh.getIndices();
  38866. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38867. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38868. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38869. var f = 0; // facet counter
  38870. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  38871. // compute size from number
  38872. if (number) {
  38873. number = (number > totalFacets) ? totalFacets : number;
  38874. size = Math.round(totalFacets / number);
  38875. delta = 0;
  38876. }
  38877. else {
  38878. size = (size > totalFacets) ? totalFacets : size;
  38879. }
  38880. var facetPos = []; // submesh positions
  38881. var facetInd = []; // submesh indices
  38882. var facetUV = []; // submesh UV
  38883. var facetCol = []; // submesh colors
  38884. var barycenter = BABYLON.Tmp.Vector3[0];
  38885. var rand;
  38886. var sizeO = size;
  38887. while (f < totalFacets) {
  38888. size = sizeO + Math.floor((1 + delta) * Math.random());
  38889. if (f > totalFacets - size) {
  38890. size = totalFacets - f;
  38891. }
  38892. // reset temp arrays
  38893. facetPos.length = 0;
  38894. facetInd.length = 0;
  38895. facetUV.length = 0;
  38896. facetCol.length = 0;
  38897. // iterate over "size" facets
  38898. var fi = 0;
  38899. for (var j = f * 3; j < (f + size) * 3; j++) {
  38900. facetInd.push(fi);
  38901. var i = meshInd[j];
  38902. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  38903. if (meshUV) {
  38904. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  38905. }
  38906. if (meshCol) {
  38907. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  38908. }
  38909. fi++;
  38910. }
  38911. // create a model shape for each single particle
  38912. var idx = this.nbParticles;
  38913. var shape = this._posToShape(facetPos);
  38914. var shapeUV = this._uvsToShapeUV(facetUV);
  38915. // compute the barycenter of the shape
  38916. var v;
  38917. for (v = 0; v < shape.length; v++) {
  38918. barycenter.addInPlace(shape[v]);
  38919. }
  38920. barycenter.scaleInPlace(1 / shape.length);
  38921. // shift the shape from its barycenter to the origin
  38922. for (v = 0; v < shape.length; v++) {
  38923. shape[v].subtractInPlace(barycenter);
  38924. }
  38925. var bInfo;
  38926. if (this._particlesIntersect) {
  38927. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  38928. }
  38929. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  38930. // add the particle in the SPS
  38931. var currentPos = this._positions.length;
  38932. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  38933. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  38934. // initialize the particle position
  38935. this.particles[this.nbParticles].position.addInPlace(barycenter);
  38936. this._index += shape.length;
  38937. idx++;
  38938. this.nbParticles++;
  38939. this._shapeCounter++;
  38940. f += size;
  38941. }
  38942. return this;
  38943. };
  38944. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  38945. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  38946. var index = 0;
  38947. var idx = 0;
  38948. for (var p = 0; p < this.particles.length; p++) {
  38949. this._particle = this.particles[p];
  38950. this._shape = this._particle._model._shape;
  38951. if (this._particle.rotationQuaternion) {
  38952. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  38953. }
  38954. else {
  38955. this._yaw = this._particle.rotation.y;
  38956. this._pitch = this._particle.rotation.x;
  38957. this._roll = this._particle.rotation.z;
  38958. this._quaternionRotationYPR();
  38959. }
  38960. this._quaternionToRotationMatrix();
  38961. this._rotMatrix.invertToRef(this._invertMatrix);
  38962. for (var pt = 0; pt < this._shape.length; pt++) {
  38963. idx = index + pt * 3;
  38964. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  38965. this._fixedNormal32[idx] = this._normal.x;
  38966. this._fixedNormal32[idx + 1] = this._normal.y;
  38967. this._fixedNormal32[idx + 2] = this._normal.z;
  38968. }
  38969. index = idx + 3;
  38970. }
  38971. };
  38972. //reset copy
  38973. SolidParticleSystem.prototype._resetCopy = function () {
  38974. this._copy.position.x = 0;
  38975. this._copy.position.y = 0;
  38976. this._copy.position.z = 0;
  38977. this._copy.rotation.x = 0;
  38978. this._copy.rotation.y = 0;
  38979. this._copy.rotation.z = 0;
  38980. this._copy.rotationQuaternion = null;
  38981. this._copy.scaling.x = 1;
  38982. this._copy.scaling.y = 1;
  38983. this._copy.scaling.z = 1;
  38984. this._copy.uvs.x = 0;
  38985. this._copy.uvs.y = 0;
  38986. this._copy.uvs.z = 1;
  38987. this._copy.uvs.w = 1;
  38988. this._copy.color = null;
  38989. };
  38990. // _meshBuilder : inserts the shape model in the global SPS mesh
  38991. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  38992. var i;
  38993. var u = 0;
  38994. var c = 0;
  38995. var n = 0;
  38996. this._resetCopy();
  38997. if (options && options.positionFunction) {
  38998. options.positionFunction(this._copy, idx, idxInShape);
  38999. this._mustUnrotateFixedNormals = true;
  39000. }
  39001. if (this._copy.rotationQuaternion) {
  39002. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  39003. }
  39004. else {
  39005. this._yaw = this._copy.rotation.y;
  39006. this._pitch = this._copy.rotation.x;
  39007. this._roll = this._copy.rotation.z;
  39008. this._quaternionRotationYPR();
  39009. }
  39010. this._quaternionToRotationMatrix();
  39011. for (i = 0; i < shape.length; i++) {
  39012. this._vertex.x = shape[i].x;
  39013. this._vertex.y = shape[i].y;
  39014. this._vertex.z = shape[i].z;
  39015. if (options && options.vertexFunction) {
  39016. options.vertexFunction(this._copy, this._vertex, i);
  39017. }
  39018. this._vertex.x *= this._copy.scaling.x;
  39019. this._vertex.y *= this._copy.scaling.y;
  39020. this._vertex.z *= this._copy.scaling.z;
  39021. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  39022. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  39023. if (meshUV) {
  39024. 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);
  39025. u += 2;
  39026. }
  39027. if (this._copy.color) {
  39028. this._color = this._copy.color;
  39029. }
  39030. else if (meshCol && meshCol[c] !== undefined) {
  39031. this._color.r = meshCol[c];
  39032. this._color.g = meshCol[c + 1];
  39033. this._color.b = meshCol[c + 2];
  39034. this._color.a = meshCol[c + 3];
  39035. }
  39036. else {
  39037. this._color.r = 1;
  39038. this._color.g = 1;
  39039. this._color.b = 1;
  39040. this._color.a = 1;
  39041. }
  39042. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  39043. c += 4;
  39044. if (!this.recomputeNormals && meshNor) {
  39045. this._normal.x = meshNor[n];
  39046. this._normal.y = meshNor[n + 1];
  39047. this._normal.z = meshNor[n + 2];
  39048. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  39049. normals.push(this._normal.x, this._normal.y, this._normal.z);
  39050. n += 3;
  39051. }
  39052. }
  39053. for (i = 0; i < meshInd.length; i++) {
  39054. indices.push(p + meshInd[i]);
  39055. }
  39056. if (this._pickable) {
  39057. var nbfaces = meshInd.length / 3;
  39058. for (i = 0; i < nbfaces; i++) {
  39059. this.pickedParticles.push({ idx: idx, faceId: i });
  39060. }
  39061. }
  39062. return this._copy;
  39063. };
  39064. // returns a shape array from positions array
  39065. SolidParticleSystem.prototype._posToShape = function (positions) {
  39066. var shape = [];
  39067. for (var i = 0; i < positions.length; i += 3) {
  39068. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  39069. }
  39070. return shape;
  39071. };
  39072. // returns a shapeUV array from a Vector4 uvs
  39073. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  39074. var shapeUV = [];
  39075. if (uvs) {
  39076. for (var i = 0; i < uvs.length; i++)
  39077. shapeUV.push(uvs[i]);
  39078. }
  39079. return shapeUV;
  39080. };
  39081. // adds a new particle object in the particles array
  39082. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  39083. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  39084. this.particles.push(sp);
  39085. return sp;
  39086. };
  39087. /**
  39088. * Adds some particles to the SPS from the model shape. Returns the shape id.
  39089. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  39090. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  39091. * `nb` (positive integer) the number of particles to be created from this model
  39092. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  39093. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  39094. */
  39095. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  39096. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39097. var meshInd = mesh.getIndices();
  39098. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39099. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39100. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39101. var bbInfo;
  39102. if (this._particlesIntersect) {
  39103. bbInfo = mesh.getBoundingInfo();
  39104. }
  39105. var shape = this._posToShape(meshPos);
  39106. var shapeUV = this._uvsToShapeUV(meshUV);
  39107. var posfunc = options ? options.positionFunction : null;
  39108. var vtxfunc = options ? options.vertexFunction : null;
  39109. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  39110. // particles
  39111. var sp;
  39112. var currentCopy;
  39113. var idx = this.nbParticles;
  39114. for (var i = 0; i < nb; i++) {
  39115. var currentPos = this._positions.length;
  39116. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  39117. if (this._updatable) {
  39118. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  39119. sp.position.copyFrom(currentCopy.position);
  39120. sp.rotation.copyFrom(currentCopy.rotation);
  39121. if (currentCopy.rotationQuaternion) {
  39122. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  39123. }
  39124. if (currentCopy.color) {
  39125. sp.color.copyFrom(currentCopy.color);
  39126. }
  39127. sp.scaling.copyFrom(currentCopy.scaling);
  39128. sp.uvs.copyFrom(currentCopy.uvs);
  39129. }
  39130. this._index += shape.length;
  39131. idx++;
  39132. }
  39133. this.nbParticles += nb;
  39134. this._shapeCounter++;
  39135. return this._shapeCounter - 1;
  39136. };
  39137. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  39138. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  39139. this._resetCopy();
  39140. if (particle._model._positionFunction) {
  39141. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  39142. }
  39143. if (this._copy.rotationQuaternion) {
  39144. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  39145. }
  39146. else {
  39147. this._yaw = this._copy.rotation.y;
  39148. this._pitch = this._copy.rotation.x;
  39149. this._roll = this._copy.rotation.z;
  39150. this._quaternionRotationYPR();
  39151. }
  39152. this._quaternionToRotationMatrix();
  39153. this._shape = particle._model._shape;
  39154. for (var pt = 0; pt < this._shape.length; pt++) {
  39155. this._vertex.x = this._shape[pt].x;
  39156. this._vertex.y = this._shape[pt].y;
  39157. this._vertex.z = this._shape[pt].z;
  39158. if (particle._model._vertexFunction) {
  39159. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  39160. }
  39161. this._vertex.x *= this._copy.scaling.x;
  39162. this._vertex.y *= this._copy.scaling.y;
  39163. this._vertex.z *= this._copy.scaling.z;
  39164. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  39165. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  39166. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  39167. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  39168. }
  39169. particle.position.x = 0.0;
  39170. particle.position.y = 0.0;
  39171. particle.position.z = 0.0;
  39172. particle.rotation.x = 0.0;
  39173. particle.rotation.y = 0.0;
  39174. particle.rotation.z = 0.0;
  39175. particle.rotationQuaternion = null;
  39176. particle.scaling.x = 1.0;
  39177. particle.scaling.y = 1.0;
  39178. particle.scaling.z = 1.0;
  39179. };
  39180. /**
  39181. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  39182. * Returns the SPS.
  39183. */
  39184. SolidParticleSystem.prototype.rebuildMesh = function () {
  39185. for (var p = 0; p < this.particles.length; p++) {
  39186. this._rebuildParticle(this.particles[p]);
  39187. }
  39188. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  39189. return this;
  39190. };
  39191. /**
  39192. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  39193. * This method calls `updateParticle()` for each particle of the SPS.
  39194. * For an animated SPS, it is usually called within the render loop.
  39195. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  39196. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  39197. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  39198. * Returns the SPS.
  39199. */
  39200. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  39201. if (start === void 0) { start = 0; }
  39202. if (end === void 0) { end = this.nbParticles - 1; }
  39203. if (update === void 0) { update = true; }
  39204. if (!this._updatable) {
  39205. return;
  39206. }
  39207. // custom beforeUpdate
  39208. this.beforeUpdateParticles(start, end, update);
  39209. this._cam_axisX.x = 1.0;
  39210. this._cam_axisX.y = 0.0;
  39211. this._cam_axisX.z = 0.0;
  39212. this._cam_axisY.x = 0.0;
  39213. this._cam_axisY.y = 1.0;
  39214. this._cam_axisY.z = 0.0;
  39215. this._cam_axisZ.x = 0.0;
  39216. this._cam_axisZ.y = 0.0;
  39217. this._cam_axisZ.z = 1.0;
  39218. // if the particles will always face the camera
  39219. if (this.billboard) {
  39220. this.mesh.computeWorldMatrix(true);
  39221. // compute the camera position and un-rotate it by the current mesh rotation
  39222. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  39223. this._quaternionToRotationMatrix();
  39224. this._rotMatrix.invertToRef(this._invertMatrix);
  39225. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  39226. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  39227. this._cam_axisZ.normalize();
  39228. // same for camera up vector extracted from the cam view matrix
  39229. var view = this._camera.getViewMatrix(true);
  39230. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  39231. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  39232. this._cam_axisY.normalize();
  39233. this._cam_axisX.normalize();
  39234. }
  39235. }
  39236. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  39237. var idx = 0; // current position index in the global array positions32
  39238. var index = 0; // position start index in the global array positions32 of the current particle
  39239. var colidx = 0; // current color index in the global array colors32
  39240. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  39241. var uvidx = 0; // current uv index in the global array uvs32
  39242. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  39243. var pt = 0; // current index in the particle model shape
  39244. if (this.mesh.isFacetDataEnabled) {
  39245. this._computeBoundingBox = true;
  39246. }
  39247. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  39248. if (this._computeBoundingBox) {
  39249. if (start == 0 && end == this.nbParticles - 1) {
  39250. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  39251. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  39252. }
  39253. else {
  39254. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  39255. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  39256. }
  39257. }
  39258. // particle loop
  39259. index = this.particles[start]._pos;
  39260. var vpos = (index / 3) | 0;
  39261. colorIndex = vpos * 4;
  39262. uvIndex = vpos * 2;
  39263. for (var p = start; p <= end; p++) {
  39264. this._particle = this.particles[p];
  39265. this._shape = this._particle._model._shape;
  39266. this._shapeUV = this._particle._model._shapeUV;
  39267. // call to custom user function to update the particle properties
  39268. this.updateParticle(this._particle);
  39269. if (this._particle.isVisible) {
  39270. // particle rotation matrix
  39271. if (this.billboard) {
  39272. this._particle.rotation.x = 0.0;
  39273. this._particle.rotation.y = 0.0;
  39274. }
  39275. if (this._computeParticleRotation || this.billboard) {
  39276. if (this._particle.rotationQuaternion) {
  39277. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  39278. }
  39279. else {
  39280. this._yaw = this._particle.rotation.y;
  39281. this._pitch = this._particle.rotation.x;
  39282. this._roll = this._particle.rotation.z;
  39283. this._quaternionRotationYPR();
  39284. }
  39285. this._quaternionToRotationMatrix();
  39286. }
  39287. // particle vertex loop
  39288. for (pt = 0; pt < this._shape.length; pt++) {
  39289. idx = index + pt * 3;
  39290. colidx = colorIndex + pt * 4;
  39291. uvidx = uvIndex + pt * 2;
  39292. this._vertex.x = this._shape[pt].x;
  39293. this._vertex.y = this._shape[pt].y;
  39294. this._vertex.z = this._shape[pt].z;
  39295. if (this._computeParticleVertex) {
  39296. this.updateParticleVertex(this._particle, this._vertex, pt);
  39297. }
  39298. // positions
  39299. this._vertex.x *= this._particle.scaling.x;
  39300. this._vertex.y *= this._particle.scaling.y;
  39301. this._vertex.z *= this._particle.scaling.z;
  39302. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  39303. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  39304. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  39305. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  39306. 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;
  39307. 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;
  39308. 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;
  39309. if (this._computeBoundingBox) {
  39310. if (this._positions32[idx] < this._minimum.x) {
  39311. this._minimum.x = this._positions32[idx];
  39312. }
  39313. if (this._positions32[idx] > this._maximum.x) {
  39314. this._maximum.x = this._positions32[idx];
  39315. }
  39316. if (this._positions32[idx + 1] < this._minimum.y) {
  39317. this._minimum.y = this._positions32[idx + 1];
  39318. }
  39319. if (this._positions32[idx + 1] > this._maximum.y) {
  39320. this._maximum.y = this._positions32[idx + 1];
  39321. }
  39322. if (this._positions32[idx + 2] < this._minimum.z) {
  39323. this._minimum.z = this._positions32[idx + 2];
  39324. }
  39325. if (this._positions32[idx + 2] > this._maximum.z) {
  39326. this._maximum.z = this._positions32[idx + 2];
  39327. }
  39328. }
  39329. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  39330. if (!this._computeParticleVertex) {
  39331. this._normal.x = this._fixedNormal32[idx];
  39332. this._normal.y = this._fixedNormal32[idx + 1];
  39333. this._normal.z = this._fixedNormal32[idx + 2];
  39334. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]);
  39335. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]);
  39336. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]);
  39337. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  39338. 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;
  39339. 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;
  39340. }
  39341. if (this._computeParticleColor) {
  39342. this._colors32[colidx] = this._particle.color.r;
  39343. this._colors32[colidx + 1] = this._particle.color.g;
  39344. this._colors32[colidx + 2] = this._particle.color.b;
  39345. this._colors32[colidx + 3] = this._particle.color.a;
  39346. }
  39347. if (this._computeParticleTexture) {
  39348. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  39349. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  39350. }
  39351. }
  39352. }
  39353. else {
  39354. for (pt = 0; pt < this._shape.length; pt++) {
  39355. idx = index + pt * 3;
  39356. colidx = colorIndex + pt * 4;
  39357. uvidx = uvIndex + pt * 2;
  39358. this._positions32[idx] = this._camera.globalPosition.x;
  39359. this._positions32[idx + 1] = this._camera.globalPosition.y;
  39360. this._positions32[idx + 2] = this._camera.globalPosition.z;
  39361. this._normals32[idx] = 0.0;
  39362. this._normals32[idx + 1] = 0.0;
  39363. this._normals32[idx + 2] = 0.0;
  39364. if (this._computeParticleColor) {
  39365. this._colors32[colidx] = this._particle.color.r;
  39366. this._colors32[colidx + 1] = this._particle.color.g;
  39367. this._colors32[colidx + 2] = this._particle.color.b;
  39368. this._colors32[colidx + 3] = this._particle.color.a;
  39369. }
  39370. if (this._computeParticleTexture) {
  39371. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  39372. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  39373. }
  39374. }
  39375. }
  39376. // if the particle intersections must be computed : update the bbInfo
  39377. if (this._particlesIntersect) {
  39378. var bInfo = this._particle._boundingInfo;
  39379. var bBox = bInfo.boundingBox;
  39380. var bSphere = bInfo.boundingSphere;
  39381. if (!this._bSphereOnly) {
  39382. // place, scale and rotate the particle bbox within the SPS local system, then update it
  39383. for (var b = 0; b < bBox.vectors.length; b++) {
  39384. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  39385. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  39386. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  39387. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  39388. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  39389. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  39390. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  39391. 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;
  39392. 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;
  39393. 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;
  39394. }
  39395. bBox._update(this.mesh._worldMatrix);
  39396. }
  39397. // place and scale the particle bouding sphere in the SPS local system, then update it
  39398. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  39399. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  39400. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  39401. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  39402. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  39403. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  39404. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  39405. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  39406. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  39407. 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));
  39408. bSphere._update(this.mesh._worldMatrix);
  39409. }
  39410. // increment indexes for the next particle
  39411. index = idx + 3;
  39412. colorIndex = colidx + 4;
  39413. uvIndex = uvidx + 2;
  39414. }
  39415. // if the VBO must be updated
  39416. if (update) {
  39417. if (this._computeParticleColor) {
  39418. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  39419. }
  39420. if (this._computeParticleTexture) {
  39421. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  39422. }
  39423. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  39424. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  39425. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  39426. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  39427. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  39428. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  39429. for (var i = 0; i < this._normals32.length; i++) {
  39430. this._fixedNormal32[i] = this._normals32[i];
  39431. }
  39432. }
  39433. if (!this.mesh.areNormalsFrozen) {
  39434. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  39435. }
  39436. }
  39437. }
  39438. if (this._computeBoundingBox) {
  39439. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  39440. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  39441. }
  39442. this.afterUpdateParticles(start, end, update);
  39443. return this;
  39444. };
  39445. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  39446. this._halfroll = this._roll * 0.5;
  39447. this._halfpitch = this._pitch * 0.5;
  39448. this._halfyaw = this._yaw * 0.5;
  39449. this._sinRoll = Math.sin(this._halfroll);
  39450. this._cosRoll = Math.cos(this._halfroll);
  39451. this._sinPitch = Math.sin(this._halfpitch);
  39452. this._cosPitch = Math.cos(this._halfpitch);
  39453. this._sinYaw = Math.sin(this._halfyaw);
  39454. this._cosYaw = Math.cos(this._halfyaw);
  39455. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  39456. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  39457. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  39458. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  39459. };
  39460. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  39461. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  39462. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  39463. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  39464. this._rotMatrix.m[3] = 0;
  39465. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  39466. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  39467. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  39468. this._rotMatrix.m[7] = 0;
  39469. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  39470. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  39471. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  39472. this._rotMatrix.m[11] = 0;
  39473. this._rotMatrix.m[12] = 0;
  39474. this._rotMatrix.m[13] = 0;
  39475. this._rotMatrix.m[14] = 0;
  39476. this._rotMatrix.m[15] = 1.0;
  39477. };
  39478. /**
  39479. * Disposes the SPS.
  39480. * Returns nothing.
  39481. */
  39482. SolidParticleSystem.prototype.dispose = function () {
  39483. this.mesh.dispose();
  39484. this.vars = null;
  39485. // drop references to internal big arrays for the GC
  39486. this._positions = null;
  39487. this._indices = null;
  39488. this._normals = null;
  39489. this._uvs = null;
  39490. this._colors = null;
  39491. this._positions32 = null;
  39492. this._normals32 = null;
  39493. this._fixedNormal32 = null;
  39494. this._uvs32 = null;
  39495. this._colors32 = null;
  39496. this.pickedParticles = null;
  39497. };
  39498. /**
  39499. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  39500. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39501. * Returns the SPS.
  39502. */
  39503. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  39504. if (!this._isVisibilityBoxLocked) {
  39505. this.mesh.refreshBoundingInfo();
  39506. }
  39507. return this;
  39508. };
  39509. /**
  39510. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  39511. * @param size the size (float) of the visibility box
  39512. * note : this doesn't lock the SPS mesh bounding box.
  39513. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39514. */
  39515. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  39516. var vis = size / 2;
  39517. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  39518. };
  39519. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  39520. // getter and setter
  39521. get: function () {
  39522. return this._alwaysVisible;
  39523. },
  39524. /**
  39525. * Sets the SPS as always visible or not
  39526. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39527. */
  39528. set: function (val) {
  39529. this._alwaysVisible = val;
  39530. this.mesh.alwaysSelectAsActiveMesh = val;
  39531. },
  39532. enumerable: true,
  39533. configurable: true
  39534. });
  39535. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  39536. get: function () {
  39537. return this._isVisibilityBoxLocked;
  39538. },
  39539. /**
  39540. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  39541. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39542. */
  39543. set: function (val) {
  39544. this._isVisibilityBoxLocked = val;
  39545. this.mesh.getBoundingInfo().isLocked = val;
  39546. },
  39547. enumerable: true,
  39548. configurable: true
  39549. });
  39550. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  39551. // getters
  39552. get: function () {
  39553. return this._computeParticleRotation;
  39554. },
  39555. // Optimizer setters
  39556. /**
  39557. * Tells to `setParticles()` to compute the particle rotations or not.
  39558. * Default value : true. The SPS is faster when it's set to false.
  39559. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  39560. */
  39561. set: function (val) {
  39562. this._computeParticleRotation = val;
  39563. },
  39564. enumerable: true,
  39565. configurable: true
  39566. });
  39567. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  39568. get: function () {
  39569. return this._computeParticleColor;
  39570. },
  39571. /**
  39572. * Tells to `setParticles()` to compute the particle colors or not.
  39573. * Default value : true. The SPS is faster when it's set to false.
  39574. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  39575. */
  39576. set: function (val) {
  39577. this._computeParticleColor = val;
  39578. },
  39579. enumerable: true,
  39580. configurable: true
  39581. });
  39582. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  39583. get: function () {
  39584. return this._computeParticleTexture;
  39585. },
  39586. /**
  39587. * Tells to `setParticles()` to compute the particle textures or not.
  39588. * Default value : true. The SPS is faster when it's set to false.
  39589. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  39590. */
  39591. set: function (val) {
  39592. this._computeParticleTexture = val;
  39593. },
  39594. enumerable: true,
  39595. configurable: true
  39596. });
  39597. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  39598. get: function () {
  39599. return this._computeParticleVertex;
  39600. },
  39601. /**
  39602. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  39603. * Default value : false. The SPS is faster when it's set to false.
  39604. * Note : the particle custom vertex positions aren't stored values.
  39605. */
  39606. set: function (val) {
  39607. this._computeParticleVertex = val;
  39608. },
  39609. enumerable: true,
  39610. configurable: true
  39611. });
  39612. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  39613. get: function () {
  39614. return this._computeBoundingBox;
  39615. },
  39616. /**
  39617. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  39618. */
  39619. set: function (val) {
  39620. this._computeBoundingBox = val;
  39621. },
  39622. enumerable: true,
  39623. configurable: true
  39624. });
  39625. // =======================================================================
  39626. // Particle behavior logic
  39627. // these following methods may be overwritten by the user to fit his needs
  39628. /**
  39629. * This function does nothing. It may be overwritten to set all the particle first values.
  39630. * The SPS doesn't call this function, you may have to call it by your own.
  39631. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39632. */
  39633. SolidParticleSystem.prototype.initParticles = function () {
  39634. };
  39635. /**
  39636. * This function does nothing. It may be overwritten to recycle a particle.
  39637. * The SPS doesn't call this function, you may have to call it by your own.
  39638. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39639. */
  39640. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  39641. return particle;
  39642. };
  39643. /**
  39644. * Updates a particle : this function should be overwritten by the user.
  39645. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  39646. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39647. * ex : just set a particle position or velocity and recycle conditions
  39648. */
  39649. SolidParticleSystem.prototype.updateParticle = function (particle) {
  39650. return particle;
  39651. };
  39652. /**
  39653. * Updates a vertex of a particle : it can be overwritten by the user.
  39654. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  39655. * @param particle the current particle
  39656. * @param vertex the current index of the current particle
  39657. * @param pt the index of the current vertex in the particle shape
  39658. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  39659. * ex : just set a vertex particle position
  39660. */
  39661. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  39662. return vertex;
  39663. };
  39664. /**
  39665. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  39666. * This does nothing and may be overwritten by the user.
  39667. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39668. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39669. * @param update the boolean update value actually passed to setParticles()
  39670. */
  39671. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  39672. };
  39673. /**
  39674. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  39675. * This will be passed three parameters.
  39676. * This does nothing and may be overwritten by the user.
  39677. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39678. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39679. * @param update the boolean update value actually passed to setParticles()
  39680. */
  39681. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  39682. };
  39683. return SolidParticleSystem;
  39684. }());
  39685. BABYLON.SolidParticleSystem = SolidParticleSystem;
  39686. })(BABYLON || (BABYLON = {}));
  39687. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  39688. /// <reference path="babylon.mesh.ts" />
  39689. var BABYLON;
  39690. (function (BABYLON) {
  39691. var GroundMesh = (function (_super) {
  39692. __extends(GroundMesh, _super);
  39693. function GroundMesh(name, scene) {
  39694. var _this = _super.call(this, name, scene) || this;
  39695. _this.generateOctree = false;
  39696. _this._worldInverse = new BABYLON.Matrix();
  39697. return _this;
  39698. }
  39699. GroundMesh.prototype.getClassName = function () {
  39700. return "GroundMesh";
  39701. };
  39702. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  39703. get: function () {
  39704. return Math.min(this._subdivisionsX, this._subdivisionsY);
  39705. },
  39706. enumerable: true,
  39707. configurable: true
  39708. });
  39709. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  39710. get: function () {
  39711. return this._subdivisionsX;
  39712. },
  39713. enumerable: true,
  39714. configurable: true
  39715. });
  39716. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  39717. get: function () {
  39718. return this._subdivisionsY;
  39719. },
  39720. enumerable: true,
  39721. configurable: true
  39722. });
  39723. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  39724. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  39725. this._subdivisionsX = chunksCount;
  39726. this._subdivisionsY = chunksCount;
  39727. this.subdivide(chunksCount);
  39728. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  39729. };
  39730. /**
  39731. * Returns a height (y) value in the Worl system :
  39732. * the ground altitude at the coordinates (x, z) expressed in the World system.
  39733. * Returns the ground y position if (x, z) are outside the ground surface.
  39734. */
  39735. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  39736. var world = this.getWorldMatrix();
  39737. var invMat = BABYLON.Tmp.Matrix[5];
  39738. world.invertToRef(invMat);
  39739. var tmpVect = BABYLON.Tmp.Vector3[8];
  39740. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  39741. x = tmpVect.x;
  39742. z = tmpVect.z;
  39743. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39744. return this.position.y;
  39745. }
  39746. if (!this._heightQuads || this._heightQuads.length == 0) {
  39747. this._initHeightQuads();
  39748. this._computeHeightQuads();
  39749. }
  39750. var facet = this._getFacetAt(x, z);
  39751. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  39752. // return y in the World system
  39753. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  39754. return tmpVect.y;
  39755. };
  39756. /**
  39757. * Returns a normalized vector (Vector3) orthogonal to the ground
  39758. * at the ground coordinates (x, z) expressed in the World system.
  39759. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  39760. */
  39761. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  39762. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  39763. this.getNormalAtCoordinatesToRef(x, z, normal);
  39764. return normal;
  39765. };
  39766. /**
  39767. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  39768. * at the ground coordinates (x, z) expressed in the World system.
  39769. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  39770. * Returns the GroundMesh.
  39771. */
  39772. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  39773. var world = this.getWorldMatrix();
  39774. var tmpMat = BABYLON.Tmp.Matrix[5];
  39775. world.invertToRef(tmpMat);
  39776. var tmpVect = BABYLON.Tmp.Vector3[8];
  39777. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  39778. x = tmpVect.x;
  39779. z = tmpVect.z;
  39780. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39781. return this;
  39782. }
  39783. if (!this._heightQuads || this._heightQuads.length == 0) {
  39784. this._initHeightQuads();
  39785. this._computeHeightQuads();
  39786. }
  39787. var facet = this._getFacetAt(x, z);
  39788. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  39789. return this;
  39790. };
  39791. /**
  39792. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  39793. * if the ground has been updated.
  39794. * This can be used in the render loop.
  39795. * Returns the GroundMesh.
  39796. */
  39797. GroundMesh.prototype.updateCoordinateHeights = function () {
  39798. if (!this._heightQuads || this._heightQuads.length == 0) {
  39799. this._initHeightQuads();
  39800. }
  39801. this._computeHeightQuads();
  39802. return this;
  39803. };
  39804. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  39805. GroundMesh.prototype._getFacetAt = function (x, z) {
  39806. // retrieve col and row from x, z coordinates in the ground local system
  39807. var subdivisionsX = this._subdivisionsX;
  39808. var subdivisionsY = this._subdivisionsY;
  39809. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  39810. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  39811. var quad = this._heightQuads[row * this._subdivisionsX + col];
  39812. var facet;
  39813. if (z < quad.slope.x * x + quad.slope.y) {
  39814. facet = quad.facet1;
  39815. }
  39816. else {
  39817. facet = quad.facet2;
  39818. }
  39819. return facet;
  39820. };
  39821. // Creates and populates the heightMap array with "facet" elements :
  39822. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  39823. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39824. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39825. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39826. // Returns the GroundMesh.
  39827. GroundMesh.prototype._initHeightQuads = function () {
  39828. var subdivisionsX = this._subdivisionsX;
  39829. var subdivisionsY = this._subdivisionsY;
  39830. this._heightQuads = new Array();
  39831. for (var row = 0; row < subdivisionsY; row++) {
  39832. for (var col = 0; col < subdivisionsX; col++) {
  39833. 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) };
  39834. this._heightQuads[row * subdivisionsX + col] = quad;
  39835. }
  39836. }
  39837. return this;
  39838. };
  39839. // Compute each quad element values and update the the heightMap array :
  39840. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39841. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39842. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39843. // Returns the GroundMesh.
  39844. GroundMesh.prototype._computeHeightQuads = function () {
  39845. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39846. var v1 = BABYLON.Tmp.Vector3[3];
  39847. var v2 = BABYLON.Tmp.Vector3[2];
  39848. var v3 = BABYLON.Tmp.Vector3[1];
  39849. var v4 = BABYLON.Tmp.Vector3[0];
  39850. var v1v2 = BABYLON.Tmp.Vector3[4];
  39851. var v1v3 = BABYLON.Tmp.Vector3[5];
  39852. var v1v4 = BABYLON.Tmp.Vector3[6];
  39853. var norm1 = BABYLON.Tmp.Vector3[7];
  39854. var norm2 = BABYLON.Tmp.Vector3[8];
  39855. var i = 0;
  39856. var j = 0;
  39857. var k = 0;
  39858. var cd = 0; // 2D slope coefficient : z = cd * x + h
  39859. var h = 0;
  39860. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  39861. var d2 = 0;
  39862. var subdivisionsX = this._subdivisionsX;
  39863. var subdivisionsY = this._subdivisionsY;
  39864. for (var row = 0; row < subdivisionsY; row++) {
  39865. for (var col = 0; col < subdivisionsX; col++) {
  39866. i = col * 3;
  39867. j = row * (subdivisionsX + 1) * 3;
  39868. k = (row + 1) * (subdivisionsX + 1) * 3;
  39869. v1.x = positions[j + i];
  39870. v1.y = positions[j + i + 1];
  39871. v1.z = positions[j + i + 2];
  39872. v2.x = positions[j + i + 3];
  39873. v2.y = positions[j + i + 4];
  39874. v2.z = positions[j + i + 5];
  39875. v3.x = positions[k + i];
  39876. v3.y = positions[k + i + 1];
  39877. v3.z = positions[k + i + 2];
  39878. v4.x = positions[k + i + 3];
  39879. v4.y = positions[k + i + 4];
  39880. v4.z = positions[k + i + 5];
  39881. // 2D slope V1V4
  39882. cd = (v4.z - v1.z) / (v4.x - v1.x);
  39883. h = v1.z - cd * v1.x; // v1 belongs to the slope
  39884. // facet equations :
  39885. // we compute each facet normal vector
  39886. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  39887. // we compute the value d by applying the equation to v1 which belongs to the plane
  39888. // then we store the facet equation in a Vector4
  39889. v2.subtractToRef(v1, v1v2);
  39890. v3.subtractToRef(v1, v1v3);
  39891. v4.subtractToRef(v1, v1v4);
  39892. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  39893. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  39894. norm1.normalize();
  39895. norm2.normalize();
  39896. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  39897. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  39898. var quad = this._heightQuads[row * subdivisionsX + col];
  39899. quad.slope.copyFromFloats(cd, h);
  39900. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  39901. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  39902. }
  39903. }
  39904. return this;
  39905. };
  39906. GroundMesh.prototype.serialize = function (serializationObject) {
  39907. _super.prototype.serialize.call(this, serializationObject);
  39908. serializationObject.subdivisionsX = this._subdivisionsX;
  39909. serializationObject.subdivisionsY = this._subdivisionsY;
  39910. serializationObject.minX = this._minX;
  39911. serializationObject.maxX = this._maxX;
  39912. serializationObject.minZ = this._minZ;
  39913. serializationObject.maxZ = this._maxZ;
  39914. serializationObject.width = this._width;
  39915. serializationObject.height = this._height;
  39916. };
  39917. GroundMesh.Parse = function (parsedMesh, scene) {
  39918. var result = new GroundMesh(parsedMesh.name, scene);
  39919. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  39920. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  39921. result._minX = parsedMesh.minX;
  39922. result._maxX = parsedMesh.maxX;
  39923. result._minZ = parsedMesh.minZ;
  39924. result._maxZ = parsedMesh.maxZ;
  39925. result._width = parsedMesh.width;
  39926. result._height = parsedMesh.height;
  39927. return result;
  39928. };
  39929. return GroundMesh;
  39930. }(BABYLON.Mesh));
  39931. BABYLON.GroundMesh = GroundMesh;
  39932. })(BABYLON || (BABYLON = {}));
  39933. //# sourceMappingURL=babylon.groundMesh.js.map
  39934. var BABYLON;
  39935. (function (BABYLON) {
  39936. /**
  39937. * Creates an instance based on a source mesh.
  39938. */
  39939. var InstancedMesh = (function (_super) {
  39940. __extends(InstancedMesh, _super);
  39941. function InstancedMesh(name, source) {
  39942. var _this = _super.call(this, name, source.getScene()) || this;
  39943. source.instances.push(_this);
  39944. _this._sourceMesh = source;
  39945. _this.position.copyFrom(source.position);
  39946. _this.rotation.copyFrom(source.rotation);
  39947. _this.scaling.copyFrom(source.scaling);
  39948. if (source.rotationQuaternion) {
  39949. _this.rotationQuaternion = source.rotationQuaternion.clone();
  39950. }
  39951. _this.infiniteDistance = source.infiniteDistance;
  39952. _this.setPivotMatrix(source.getPivotMatrix());
  39953. _this.refreshBoundingInfo();
  39954. _this._syncSubMeshes();
  39955. return _this;
  39956. }
  39957. /**
  39958. * Returns the string "InstancedMesh".
  39959. */
  39960. InstancedMesh.prototype.getClassName = function () {
  39961. return "InstancedMesh";
  39962. };
  39963. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  39964. // Methods
  39965. get: function () {
  39966. return this._sourceMesh.receiveShadows;
  39967. },
  39968. enumerable: true,
  39969. configurable: true
  39970. });
  39971. Object.defineProperty(InstancedMesh.prototype, "material", {
  39972. get: function () {
  39973. return this._sourceMesh.material;
  39974. },
  39975. enumerable: true,
  39976. configurable: true
  39977. });
  39978. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  39979. get: function () {
  39980. return this._sourceMesh.visibility;
  39981. },
  39982. enumerable: true,
  39983. configurable: true
  39984. });
  39985. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  39986. get: function () {
  39987. return this._sourceMesh.skeleton;
  39988. },
  39989. enumerable: true,
  39990. configurable: true
  39991. });
  39992. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  39993. get: function () {
  39994. return this._sourceMesh.renderingGroupId;
  39995. },
  39996. enumerable: true,
  39997. configurable: true
  39998. });
  39999. /**
  40000. * Returns the total number of vertices (integer).
  40001. */
  40002. InstancedMesh.prototype.getTotalVertices = function () {
  40003. return this._sourceMesh.getTotalVertices();
  40004. };
  40005. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  40006. get: function () {
  40007. return this._sourceMesh;
  40008. },
  40009. enumerable: true,
  40010. configurable: true
  40011. });
  40012. /**
  40013. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  40014. */
  40015. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  40016. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  40017. };
  40018. /**
  40019. * Sets the vertex data of the mesh geometry for the requested `kind`.
  40020. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  40021. * The `data` are either a numeric array either a Float32Array.
  40022. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  40023. * 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).
  40024. * Note that a new underlying VertexBuffer object is created each call.
  40025. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  40026. *
  40027. * Possible `kind` values :
  40028. * - BABYLON.VertexBuffer.PositionKind
  40029. * - BABYLON.VertexBuffer.UVKind
  40030. * - BABYLON.VertexBuffer.UV2Kind
  40031. * - BABYLON.VertexBuffer.UV3Kind
  40032. * - BABYLON.VertexBuffer.UV4Kind
  40033. * - BABYLON.VertexBuffer.UV5Kind
  40034. * - BABYLON.VertexBuffer.UV6Kind
  40035. * - BABYLON.VertexBuffer.ColorKind
  40036. * - BABYLON.VertexBuffer.MatricesIndicesKind
  40037. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  40038. * - BABYLON.VertexBuffer.MatricesWeightsKind
  40039. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  40040. *
  40041. * Returns the Mesh.
  40042. */
  40043. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40044. if (this.sourceMesh) {
  40045. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  40046. }
  40047. return this.sourceMesh;
  40048. };
  40049. /**
  40050. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  40051. * If the mesh has no geometry, it is simply returned as it is.
  40052. * The `data` are either a numeric array either a Float32Array.
  40053. * No new underlying VertexBuffer object is created.
  40054. * 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.
  40055. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  40056. *
  40057. * Possible `kind` values :
  40058. * - BABYLON.VertexBuffer.PositionKind
  40059. * - BABYLON.VertexBuffer.UVKind
  40060. * - BABYLON.VertexBuffer.UV2Kind
  40061. * - BABYLON.VertexBuffer.UV3Kind
  40062. * - BABYLON.VertexBuffer.UV4Kind
  40063. * - BABYLON.VertexBuffer.UV5Kind
  40064. * - BABYLON.VertexBuffer.UV6Kind
  40065. * - BABYLON.VertexBuffer.ColorKind
  40066. * - BABYLON.VertexBuffer.MatricesIndicesKind
  40067. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  40068. * - BABYLON.VertexBuffer.MatricesWeightsKind
  40069. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  40070. *
  40071. * Returns the Mesh.
  40072. */
  40073. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  40074. if (this.sourceMesh) {
  40075. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  40076. }
  40077. return this.sourceMesh;
  40078. };
  40079. /**
  40080. * Sets the mesh indices.
  40081. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  40082. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  40083. * This method creates a new index buffer each call.
  40084. * Returns the Mesh.
  40085. */
  40086. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  40087. if (this.sourceMesh) {
  40088. this.sourceMesh.setIndices(indices, totalVertices);
  40089. }
  40090. return this.sourceMesh;
  40091. };
  40092. /**
  40093. * Boolean : True if the mesh owns the requested kind of data.
  40094. */
  40095. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  40096. return this._sourceMesh.isVerticesDataPresent(kind);
  40097. };
  40098. /**
  40099. * Returns an array of indices (IndicesArray).
  40100. */
  40101. InstancedMesh.prototype.getIndices = function () {
  40102. return this._sourceMesh.getIndices();
  40103. };
  40104. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  40105. get: function () {
  40106. return this._sourceMesh._positions;
  40107. },
  40108. enumerable: true,
  40109. configurable: true
  40110. });
  40111. /**
  40112. * Sets a new updated BoundingInfo to the mesh.
  40113. * Returns the mesh.
  40114. */
  40115. InstancedMesh.prototype.refreshBoundingInfo = function () {
  40116. var meshBB = this._sourceMesh.getBoundingInfo();
  40117. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  40118. this._updateBoundingInfo();
  40119. return this;
  40120. };
  40121. InstancedMesh.prototype._preActivate = function () {
  40122. if (this._currentLOD) {
  40123. this._currentLOD._preActivate();
  40124. }
  40125. return this;
  40126. };
  40127. InstancedMesh.prototype._activate = function (renderId) {
  40128. if (this._currentLOD) {
  40129. this._currentLOD._registerInstanceForRenderId(this, renderId);
  40130. }
  40131. return this;
  40132. };
  40133. /**
  40134. * Returns the current associated LOD AbstractMesh.
  40135. */
  40136. InstancedMesh.prototype.getLOD = function (camera) {
  40137. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  40138. if (this._currentLOD === this.sourceMesh) {
  40139. return this;
  40140. }
  40141. return this._currentLOD;
  40142. };
  40143. InstancedMesh.prototype._syncSubMeshes = function () {
  40144. this.releaseSubMeshes();
  40145. if (this._sourceMesh.subMeshes) {
  40146. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  40147. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  40148. }
  40149. }
  40150. return this;
  40151. };
  40152. InstancedMesh.prototype._generatePointsArray = function () {
  40153. return this._sourceMesh._generatePointsArray();
  40154. };
  40155. /**
  40156. * Creates a new InstancedMesh from the current mesh.
  40157. * - name (string) : the cloned mesh name
  40158. * - newParent (optional Node) : the optional Node to parent the clone to.
  40159. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  40160. *
  40161. * Returns the clone.
  40162. */
  40163. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  40164. var result = this._sourceMesh.createInstance(name);
  40165. // Deep copy
  40166. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  40167. // Bounding info
  40168. this.refreshBoundingInfo();
  40169. // Parent
  40170. if (newParent) {
  40171. result.parent = newParent;
  40172. }
  40173. if (!doNotCloneChildren) {
  40174. // Children
  40175. for (var index = 0; index < this.getScene().meshes.length; index++) {
  40176. var mesh = this.getScene().meshes[index];
  40177. if (mesh.parent === this) {
  40178. mesh.clone(mesh.name, result);
  40179. }
  40180. }
  40181. }
  40182. result.computeWorldMatrix(true);
  40183. return result;
  40184. };
  40185. /**
  40186. * Disposes the InstancedMesh.
  40187. * Returns nothing.
  40188. */
  40189. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  40190. // Remove from mesh
  40191. var index = this._sourceMesh.instances.indexOf(this);
  40192. this._sourceMesh.instances.splice(index, 1);
  40193. _super.prototype.dispose.call(this, doNotRecurse);
  40194. };
  40195. return InstancedMesh;
  40196. }(BABYLON.AbstractMesh));
  40197. BABYLON.InstancedMesh = InstancedMesh;
  40198. })(BABYLON || (BABYLON = {}));
  40199. //# sourceMappingURL=babylon.instancedMesh.js.map
  40200. /// <reference path="babylon.mesh.ts" />
  40201. var BABYLON;
  40202. (function (BABYLON) {
  40203. var LinesMesh = (function (_super) {
  40204. __extends(LinesMesh, _super);
  40205. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  40206. if (parent === void 0) { parent = null; }
  40207. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  40208. _this.useVertexColor = useVertexColor;
  40209. _this.color = new BABYLON.Color3(1, 1, 1);
  40210. _this.alpha = 1;
  40211. if (source) {
  40212. _this.color = source.color.clone();
  40213. _this.alpha = source.alpha;
  40214. _this.useVertexColor = source.useVertexColor;
  40215. }
  40216. _this._intersectionThreshold = 0.1;
  40217. var options = {
  40218. attributes: [BABYLON.VertexBuffer.PositionKind],
  40219. uniforms: ["world", "viewProjection"],
  40220. needAlphaBlending: false,
  40221. };
  40222. if (!useVertexColor) {
  40223. options.uniforms.push("color");
  40224. options.needAlphaBlending = true;
  40225. }
  40226. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  40227. return _this;
  40228. }
  40229. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  40230. /**
  40231. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  40232. * This margin is expressed in world space coordinates, so its value may vary.
  40233. * Default value is 0.1
  40234. * @returns the intersection Threshold value.
  40235. */
  40236. get: function () {
  40237. return this._intersectionThreshold;
  40238. },
  40239. /**
  40240. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  40241. * This margin is expressed in world space coordinates, so its value may vary.
  40242. * @param value the new threshold to apply
  40243. */
  40244. set: function (value) {
  40245. if (this._intersectionThreshold === value) {
  40246. return;
  40247. }
  40248. this._intersectionThreshold = value;
  40249. if (this.geometry) {
  40250. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  40251. }
  40252. },
  40253. enumerable: true,
  40254. configurable: true
  40255. });
  40256. /**
  40257. * Returns the string "LineMesh"
  40258. */
  40259. LinesMesh.prototype.getClassName = function () {
  40260. return "LinesMesh";
  40261. };
  40262. Object.defineProperty(LinesMesh.prototype, "material", {
  40263. get: function () {
  40264. return this._colorShader;
  40265. },
  40266. enumerable: true,
  40267. configurable: true
  40268. });
  40269. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  40270. get: function () {
  40271. return false;
  40272. },
  40273. enumerable: true,
  40274. configurable: true
  40275. });
  40276. LinesMesh.prototype.createInstance = function (name) {
  40277. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  40278. return null;
  40279. };
  40280. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  40281. // VBOs
  40282. this._geometry._bind(this._colorShader.getEffect());
  40283. // Color
  40284. if (!this.useVertexColor) {
  40285. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  40286. }
  40287. return this;
  40288. };
  40289. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  40290. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  40291. return this;
  40292. }
  40293. var engine = this.getScene().getEngine();
  40294. // Draw order
  40295. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  40296. return this;
  40297. };
  40298. LinesMesh.prototype.dispose = function (doNotRecurse) {
  40299. this._colorShader.dispose();
  40300. _super.prototype.dispose.call(this, doNotRecurse);
  40301. };
  40302. /**
  40303. * Returns a new LineMesh object cloned from the current one.
  40304. */
  40305. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  40306. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  40307. };
  40308. return LinesMesh;
  40309. }(BABYLON.Mesh));
  40310. BABYLON.LinesMesh = LinesMesh;
  40311. })(BABYLON || (BABYLON = {}));
  40312. //# sourceMappingURL=babylon.linesMesh.js.map
  40313. var BABYLON;
  40314. (function (BABYLON) {
  40315. var ShaderMaterial = (function (_super) {
  40316. __extends(ShaderMaterial, _super);
  40317. function ShaderMaterial(name, scene, shaderPath, options) {
  40318. var _this = _super.call(this, name, scene) || this;
  40319. _this._textures = {};
  40320. _this._textureArrays = {};
  40321. _this._floats = {};
  40322. _this._floatsArrays = {};
  40323. _this._colors3 = {};
  40324. _this._colors4 = {};
  40325. _this._vectors2 = {};
  40326. _this._vectors3 = {};
  40327. _this._vectors4 = {};
  40328. _this._matrices = {};
  40329. _this._matrices3x3 = {};
  40330. _this._matrices2x2 = {};
  40331. _this._vectors3Arrays = {};
  40332. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  40333. _this._shaderPath = shaderPath;
  40334. options.needAlphaBlending = options.needAlphaBlending || false;
  40335. options.needAlphaTesting = options.needAlphaTesting || false;
  40336. options.attributes = options.attributes || ["position", "normal", "uv"];
  40337. options.uniforms = options.uniforms || ["worldViewProjection"];
  40338. options.uniformBuffers = options.uniformBuffers || [];
  40339. options.samplers = options.samplers || [];
  40340. options.defines = options.defines || [];
  40341. _this._options = options;
  40342. return _this;
  40343. }
  40344. ShaderMaterial.prototype.getClassName = function () {
  40345. return "ShaderMaterial";
  40346. };
  40347. ShaderMaterial.prototype.needAlphaBlending = function () {
  40348. return this._options.needAlphaBlending;
  40349. };
  40350. ShaderMaterial.prototype.needAlphaTesting = function () {
  40351. return this._options.needAlphaTesting;
  40352. };
  40353. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  40354. if (this._options.uniforms.indexOf(uniformName) === -1) {
  40355. this._options.uniforms.push(uniformName);
  40356. }
  40357. };
  40358. ShaderMaterial.prototype.setTexture = function (name, texture) {
  40359. if (this._options.samplers.indexOf(name) === -1) {
  40360. this._options.samplers.push(name);
  40361. }
  40362. this._textures[name] = texture;
  40363. return this;
  40364. };
  40365. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  40366. if (this._options.samplers.indexOf(name) === -1) {
  40367. this._options.samplers.push(name);
  40368. }
  40369. this._checkUniform(name);
  40370. this._textureArrays[name] = textures;
  40371. return this;
  40372. };
  40373. ShaderMaterial.prototype.setFloat = function (name, value) {
  40374. this._checkUniform(name);
  40375. this._floats[name] = value;
  40376. return this;
  40377. };
  40378. ShaderMaterial.prototype.setFloats = function (name, value) {
  40379. this._checkUniform(name);
  40380. this._floatsArrays[name] = value;
  40381. return this;
  40382. };
  40383. ShaderMaterial.prototype.setColor3 = function (name, value) {
  40384. this._checkUniform(name);
  40385. this._colors3[name] = value;
  40386. return this;
  40387. };
  40388. ShaderMaterial.prototype.setColor4 = function (name, value) {
  40389. this._checkUniform(name);
  40390. this._colors4[name] = value;
  40391. return this;
  40392. };
  40393. ShaderMaterial.prototype.setVector2 = function (name, value) {
  40394. this._checkUniform(name);
  40395. this._vectors2[name] = value;
  40396. return this;
  40397. };
  40398. ShaderMaterial.prototype.setVector3 = function (name, value) {
  40399. this._checkUniform(name);
  40400. this._vectors3[name] = value;
  40401. return this;
  40402. };
  40403. ShaderMaterial.prototype.setVector4 = function (name, value) {
  40404. this._checkUniform(name);
  40405. this._vectors4[name] = value;
  40406. return this;
  40407. };
  40408. ShaderMaterial.prototype.setMatrix = function (name, value) {
  40409. this._checkUniform(name);
  40410. this._matrices[name] = value;
  40411. return this;
  40412. };
  40413. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  40414. this._checkUniform(name);
  40415. this._matrices3x3[name] = value;
  40416. return this;
  40417. };
  40418. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  40419. this._checkUniform(name);
  40420. this._matrices2x2[name] = value;
  40421. return this;
  40422. };
  40423. ShaderMaterial.prototype.setArray3 = function (name, value) {
  40424. this._checkUniform(name);
  40425. this._vectors3Arrays[name] = value;
  40426. return this;
  40427. };
  40428. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  40429. if (!mesh) {
  40430. return true;
  40431. }
  40432. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  40433. return false;
  40434. }
  40435. return false;
  40436. };
  40437. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  40438. var scene = this.getScene();
  40439. var engine = scene.getEngine();
  40440. if (!this.checkReadyOnEveryCall) {
  40441. if (this._renderId === scene.getRenderId()) {
  40442. if (this._checkCache(scene, mesh, useInstances)) {
  40443. return true;
  40444. }
  40445. }
  40446. }
  40447. // Instances
  40448. var defines = [];
  40449. var attribs = [];
  40450. var fallbacks = new BABYLON.EffectFallbacks();
  40451. if (useInstances) {
  40452. defines.push("#define INSTANCES");
  40453. }
  40454. for (var index = 0; index < this._options.defines.length; index++) {
  40455. defines.push(this._options.defines[index]);
  40456. }
  40457. for (var index = 0; index < this._options.attributes.length; index++) {
  40458. attribs.push(this._options.attributes[index]);
  40459. }
  40460. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40461. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40462. defines.push("#define VERTEXCOLOR");
  40463. }
  40464. // Bones
  40465. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40466. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40467. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40468. if (mesh.numBoneInfluencers > 4) {
  40469. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40470. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40471. }
  40472. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40473. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40474. fallbacks.addCPUSkinningFallback(0, mesh);
  40475. if (this._options.uniforms.indexOf("mBones") === -1) {
  40476. this._options.uniforms.push("mBones");
  40477. }
  40478. }
  40479. else {
  40480. defines.push("#define NUM_BONE_INFLUENCERS 0");
  40481. }
  40482. // Textures
  40483. for (var name in this._textures) {
  40484. if (!this._textures[name].isReady()) {
  40485. return false;
  40486. }
  40487. }
  40488. // Alpha test
  40489. if (engine.getAlphaTesting()) {
  40490. defines.push("#define ALPHATEST");
  40491. }
  40492. var previousEffect = this._effect;
  40493. var join = defines.join("\n");
  40494. this._effect = engine.createEffect(this._shaderPath, {
  40495. attributes: attribs,
  40496. uniformsNames: this._options.uniforms,
  40497. uniformBuffersNames: this._options.uniformBuffers,
  40498. samplers: this._options.samplers,
  40499. defines: join,
  40500. fallbacks: fallbacks,
  40501. onCompiled: this.onCompiled,
  40502. onError: this.onError
  40503. }, engine);
  40504. if (!this._effect.isReady()) {
  40505. return false;
  40506. }
  40507. if (previousEffect !== this._effect) {
  40508. scene.resetCachedMaterial();
  40509. }
  40510. this._renderId = scene.getRenderId();
  40511. return true;
  40512. };
  40513. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40514. var scene = this.getScene();
  40515. if (this._options.uniforms.indexOf("world") !== -1) {
  40516. this._effect.setMatrix("world", world);
  40517. }
  40518. if (this._options.uniforms.indexOf("worldView") !== -1) {
  40519. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  40520. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  40521. }
  40522. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  40523. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  40524. }
  40525. };
  40526. ShaderMaterial.prototype.bind = function (world, mesh) {
  40527. // Std values
  40528. this.bindOnlyWorldMatrix(world);
  40529. if (this.getScene().getCachedMaterial() !== this) {
  40530. if (this._options.uniforms.indexOf("view") !== -1) {
  40531. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  40532. }
  40533. if (this._options.uniforms.indexOf("projection") !== -1) {
  40534. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  40535. }
  40536. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  40537. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  40538. }
  40539. // Bones
  40540. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  40541. var name;
  40542. // Texture
  40543. for (name in this._textures) {
  40544. this._effect.setTexture(name, this._textures[name]);
  40545. }
  40546. // Texture arrays
  40547. for (name in this._textureArrays) {
  40548. this._effect.setTextureArray(name, this._textureArrays[name]);
  40549. }
  40550. // Float
  40551. for (name in this._floats) {
  40552. this._effect.setFloat(name, this._floats[name]);
  40553. }
  40554. // Float s
  40555. for (name in this._floatsArrays) {
  40556. this._effect.setArray(name, this._floatsArrays[name]);
  40557. }
  40558. // Color3
  40559. for (name in this._colors3) {
  40560. this._effect.setColor3(name, this._colors3[name]);
  40561. }
  40562. // Color4
  40563. for (name in this._colors4) {
  40564. var color = this._colors4[name];
  40565. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40566. }
  40567. // Vector2
  40568. for (name in this._vectors2) {
  40569. this._effect.setVector2(name, this._vectors2[name]);
  40570. }
  40571. // Vector3
  40572. for (name in this._vectors3) {
  40573. this._effect.setVector3(name, this._vectors3[name]);
  40574. }
  40575. // Vector4
  40576. for (name in this._vectors4) {
  40577. this._effect.setVector4(name, this._vectors4[name]);
  40578. }
  40579. // Matrix
  40580. for (name in this._matrices) {
  40581. this._effect.setMatrix(name, this._matrices[name]);
  40582. }
  40583. // Matrix 3x3
  40584. for (name in this._matrices3x3) {
  40585. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40586. }
  40587. // Matrix 2x2
  40588. for (name in this._matrices2x2) {
  40589. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40590. }
  40591. // Vector3Array
  40592. for (name in this._vectors3Arrays) {
  40593. this._effect.setArray3(name, this._vectors3Arrays[name]);
  40594. }
  40595. }
  40596. this._afterBind(mesh);
  40597. };
  40598. ShaderMaterial.prototype.getActiveTextures = function () {
  40599. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40600. for (var name in this._textures) {
  40601. activeTextures.push(this._textures[name]);
  40602. }
  40603. for (var name in this._textureArrays) {
  40604. var array = this._textureArrays[name];
  40605. for (var index = 0; index < array.length; index++) {
  40606. activeTextures.push(array[index]);
  40607. }
  40608. }
  40609. return activeTextures;
  40610. };
  40611. ShaderMaterial.prototype.clone = function (name) {
  40612. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40613. return newShaderMaterial;
  40614. };
  40615. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40616. if (forceDisposeTextures) {
  40617. var name;
  40618. for (name in this._textures) {
  40619. this._textures[name].dispose();
  40620. }
  40621. for (name in this._textureArrays) {
  40622. var array = this._textureArrays[name];
  40623. for (var index = 0; index < array.length; index++) {
  40624. array[index].dispose();
  40625. }
  40626. }
  40627. }
  40628. this._textures = {};
  40629. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40630. };
  40631. ShaderMaterial.prototype.serialize = function () {
  40632. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40633. serializationObject.customType = "BABYLON.ShaderMaterial";
  40634. serializationObject.options = this._options;
  40635. serializationObject.shaderPath = this._shaderPath;
  40636. var name;
  40637. // Texture
  40638. serializationObject.textures = {};
  40639. for (name in this._textures) {
  40640. serializationObject.textures[name] = this._textures[name].serialize();
  40641. }
  40642. // Texture arrays
  40643. serializationObject.textureArrays = {};
  40644. for (name in this._textureArrays) {
  40645. serializationObject.textureArrays[name] = [];
  40646. var array = this._textureArrays[name];
  40647. for (var index = 0; index < array.length; index++) {
  40648. serializationObject.textureArrays[name].push(array[index].serialize());
  40649. }
  40650. }
  40651. // Float
  40652. serializationObject.floats = {};
  40653. for (name in this._floats) {
  40654. serializationObject.floats[name] = this._floats[name];
  40655. }
  40656. // Float s
  40657. serializationObject.floatArrays = {};
  40658. for (name in this._floatsArrays) {
  40659. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40660. }
  40661. // Color3
  40662. serializationObject.colors3 = {};
  40663. for (name in this._colors3) {
  40664. serializationObject.colors3[name] = this._colors3[name].asArray();
  40665. }
  40666. // Color4
  40667. serializationObject.colors4 = {};
  40668. for (name in this._colors4) {
  40669. serializationObject.colors4[name] = this._colors4[name].asArray();
  40670. }
  40671. // Vector2
  40672. serializationObject.vectors2 = {};
  40673. for (name in this._vectors2) {
  40674. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40675. }
  40676. // Vector3
  40677. serializationObject.vectors3 = {};
  40678. for (name in this._vectors3) {
  40679. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40680. }
  40681. // Vector4
  40682. serializationObject.vectors4 = {};
  40683. for (name in this._vectors4) {
  40684. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40685. }
  40686. // Matrix
  40687. serializationObject.matrices = {};
  40688. for (name in this._matrices) {
  40689. serializationObject.matrices[name] = this._matrices[name].asArray();
  40690. }
  40691. // Matrix 3x3
  40692. serializationObject.matrices3x3 = {};
  40693. for (name in this._matrices3x3) {
  40694. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40695. }
  40696. // Matrix 2x2
  40697. serializationObject.matrices2x2 = {};
  40698. for (name in this._matrices2x2) {
  40699. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40700. }
  40701. // Vector3Array
  40702. serializationObject.vectors3Arrays = {};
  40703. for (name in this._vectors3Arrays) {
  40704. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40705. }
  40706. return serializationObject;
  40707. };
  40708. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40709. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40710. var name;
  40711. // Texture
  40712. for (name in source.textures) {
  40713. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40714. }
  40715. // Texture arrays
  40716. for (name in source.textureArrays) {
  40717. var array = source.textureArrays[name];
  40718. var textureArray = new Array();
  40719. for (var index = 0; index < array.length; index++) {
  40720. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  40721. }
  40722. material.setTextureArray(name, textureArray);
  40723. }
  40724. // Float
  40725. for (name in source.floats) {
  40726. material.setFloat(name, source.floats[name]);
  40727. }
  40728. // Float s
  40729. for (name in source.floatsArrays) {
  40730. material.setFloats(name, source.floatsArrays[name]);
  40731. }
  40732. // Color3
  40733. for (name in source.colors3) {
  40734. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40735. }
  40736. // Color4
  40737. for (name in source.colors4) {
  40738. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40739. }
  40740. // Vector2
  40741. for (name in source.vectors2) {
  40742. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40743. }
  40744. // Vector3
  40745. for (name in source.vectors3) {
  40746. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40747. }
  40748. // Vector4
  40749. for (name in source.vectors4) {
  40750. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40751. }
  40752. // Matrix
  40753. for (name in source.matrices) {
  40754. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40755. }
  40756. // Matrix 3x3
  40757. for (name in source.matrices3x3) {
  40758. material.setMatrix3x3(name, source.matrices3x3[name]);
  40759. }
  40760. // Matrix 2x2
  40761. for (name in source.matrices2x2) {
  40762. material.setMatrix2x2(name, source.matrices2x2[name]);
  40763. }
  40764. // Vector3Array
  40765. for (name in source.vectors3Arrays) {
  40766. material.setArray3(name, source.vectors3Arrays[name]);
  40767. }
  40768. return material;
  40769. };
  40770. return ShaderMaterial;
  40771. }(BABYLON.Material));
  40772. BABYLON.ShaderMaterial = ShaderMaterial;
  40773. })(BABYLON || (BABYLON = {}));
  40774. //# sourceMappingURL=babylon.shaderMaterial.js.map
  40775. var BABYLON;
  40776. (function (BABYLON) {
  40777. var MeshBuilder = (function () {
  40778. function MeshBuilder() {
  40779. }
  40780. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  40781. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  40782. return BABYLON.Mesh.DOUBLESIDE;
  40783. }
  40784. if (orientation === undefined || orientation === null) {
  40785. return BABYLON.Mesh.FRONTSIDE;
  40786. }
  40787. return orientation;
  40788. };
  40789. /**
  40790. * Creates a box mesh.
  40791. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  40792. * The parameter `size` sets the size (float) of each box side (default 1).
  40793. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  40794. * 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).
  40795. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40796. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40797. * 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).
  40798. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40799. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40800. */
  40801. MeshBuilder.CreateBox = function (name, options, scene) {
  40802. var box = new BABYLON.Mesh(name, scene);
  40803. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40804. box.sideOrientation = options.sideOrientation;
  40805. var vertexData = BABYLON.VertexData.CreateBox(options);
  40806. vertexData.applyToMesh(box, options.updatable);
  40807. return box;
  40808. };
  40809. /**
  40810. * Creates a sphere mesh.
  40811. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  40812. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  40813. * 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`).
  40814. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  40815. * 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
  40816. * 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).
  40817. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40818. * 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).
  40819. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40821. */
  40822. MeshBuilder.CreateSphere = function (name, options, scene) {
  40823. var sphere = new BABYLON.Mesh(name, scene);
  40824. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40825. sphere.sideOrientation = options.sideOrientation;
  40826. var vertexData = BABYLON.VertexData.CreateSphere(options);
  40827. vertexData.applyToMesh(sphere, options.updatable);
  40828. return sphere;
  40829. };
  40830. /**
  40831. * Creates a plane polygonal mesh. By default, this is a disc.
  40832. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  40833. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  40834. * 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.
  40835. * 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
  40836. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40837. * 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).
  40838. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40839. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40840. */
  40841. MeshBuilder.CreateDisc = function (name, options, scene) {
  40842. var disc = new BABYLON.Mesh(name, scene);
  40843. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40844. disc.sideOrientation = options.sideOrientation;
  40845. var vertexData = BABYLON.VertexData.CreateDisc(options);
  40846. vertexData.applyToMesh(disc, options.updatable);
  40847. return disc;
  40848. };
  40849. /**
  40850. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  40851. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  40852. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  40853. * 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`).
  40854. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  40855. * 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.
  40856. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40857. * 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).
  40858. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40859. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40860. */
  40861. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  40862. var sphere = new BABYLON.Mesh(name, scene);
  40863. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40864. sphere.sideOrientation = options.sideOrientation;
  40865. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  40866. vertexData.applyToMesh(sphere, options.updatable);
  40867. return sphere;
  40868. };
  40869. ;
  40870. /**
  40871. * Creates a ribbon mesh.
  40872. * 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.
  40873. *
  40874. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  40875. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  40876. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  40877. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  40878. * 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.
  40879. * 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.
  40880. * 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
  40881. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40882. * 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).
  40883. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40884. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40885. * 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.
  40886. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  40887. * 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
  40888. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  40889. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  40890. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40891. */
  40892. MeshBuilder.CreateRibbon = function (name, options, scene) {
  40893. var pathArray = options.pathArray;
  40894. var closeArray = options.closeArray;
  40895. var closePath = options.closePath;
  40896. var offset = options.offset;
  40897. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40898. var instance = options.instance;
  40899. var updatable = options.updatable;
  40900. if (instance) {
  40901. // positionFunction : ribbon case
  40902. // only pathArray and sideOrientation parameters are taken into account for positions update
  40903. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  40904. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  40905. var positionFunction = function (positions) {
  40906. var minlg = pathArray[0].length;
  40907. var i = 0;
  40908. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  40909. for (var si = 1; si <= ns; si++) {
  40910. for (var p = 0; p < pathArray.length; p++) {
  40911. var path = pathArray[p];
  40912. var l = path.length;
  40913. minlg = (minlg < l) ? minlg : l;
  40914. var j = 0;
  40915. while (j < minlg) {
  40916. positions[i] = path[j].x;
  40917. positions[i + 1] = path[j].y;
  40918. positions[i + 2] = path[j].z;
  40919. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  40920. BABYLON.Tmp.Vector3[0].x = path[j].x;
  40921. }
  40922. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  40923. BABYLON.Tmp.Vector3[1].x = path[j].x;
  40924. }
  40925. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  40926. BABYLON.Tmp.Vector3[0].y = path[j].y;
  40927. }
  40928. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  40929. BABYLON.Tmp.Vector3[1].y = path[j].y;
  40930. }
  40931. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  40932. BABYLON.Tmp.Vector3[0].z = path[j].z;
  40933. }
  40934. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  40935. BABYLON.Tmp.Vector3[1].z = path[j].z;
  40936. }
  40937. j++;
  40938. i += 3;
  40939. }
  40940. if (instance._closePath) {
  40941. positions[i] = path[0].x;
  40942. positions[i + 1] = path[0].y;
  40943. positions[i + 2] = path[0].z;
  40944. i += 3;
  40945. }
  40946. }
  40947. }
  40948. };
  40949. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40950. positionFunction(positions);
  40951. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  40952. instance._boundingInfo.update(instance._worldMatrix);
  40953. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  40954. if (options.colors) {
  40955. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40956. for (var c = 0; c < options.colors.length; c++) {
  40957. colors[c * 4] = options.colors[c].r;
  40958. colors[c * 4 + 1] = options.colors[c].g;
  40959. colors[c * 4 + 2] = options.colors[c].b;
  40960. colors[c * 4 + 3] = options.colors[c].a;
  40961. }
  40962. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  40963. }
  40964. if (options.uvs) {
  40965. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40966. for (var i = 0; i < options.uvs.length; i++) {
  40967. uvs[i * 2] = options.uvs[i].x;
  40968. uvs[i * 2 + 1] = options.uvs[i].y;
  40969. }
  40970. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  40971. }
  40972. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  40973. var indices = instance.getIndices();
  40974. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40975. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  40976. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  40977. if (instance._closePath) {
  40978. var indexFirst = 0;
  40979. var indexLast = 0;
  40980. for (var p = 0; p < pathArray.length; p++) {
  40981. indexFirst = instance._idx[p] * 3;
  40982. if (p + 1 < pathArray.length) {
  40983. indexLast = (instance._idx[p + 1] - 1) * 3;
  40984. }
  40985. else {
  40986. indexLast = normals.length - 3;
  40987. }
  40988. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  40989. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  40990. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  40991. normals[indexLast] = normals[indexFirst];
  40992. normals[indexLast + 1] = normals[indexFirst + 1];
  40993. normals[indexLast + 2] = normals[indexFirst + 2];
  40994. }
  40995. }
  40996. if (!(instance.areNormalsFrozen)) {
  40997. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  40998. }
  40999. }
  41000. return instance;
  41001. }
  41002. else {
  41003. var ribbon = new BABYLON.Mesh(name, scene);
  41004. ribbon.sideOrientation = sideOrientation;
  41005. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  41006. if (closePath) {
  41007. ribbon._idx = vertexData._idx;
  41008. }
  41009. ribbon._closePath = closePath;
  41010. ribbon._closeArray = closeArray;
  41011. vertexData.applyToMesh(ribbon, updatable);
  41012. return ribbon;
  41013. }
  41014. };
  41015. /**
  41016. * Creates a cylinder or a cone mesh.
  41017. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  41018. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  41019. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  41020. * 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.
  41021. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  41022. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  41023. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  41024. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  41025. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  41026. * 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).
  41027. * 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
  41028. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  41029. * 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
  41030. * 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.
  41031. * If `enclose` is false, a ring surface is one element.
  41032. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  41033. * 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
  41034. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41035. * 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).
  41036. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41037. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41038. */
  41039. MeshBuilder.CreateCylinder = function (name, options, scene) {
  41040. var cylinder = new BABYLON.Mesh(name, scene);
  41041. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41042. cylinder.sideOrientation = options.sideOrientation;
  41043. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  41044. vertexData.applyToMesh(cylinder, options.updatable);
  41045. return cylinder;
  41046. };
  41047. /**
  41048. * Creates a torus mesh.
  41049. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  41050. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  41051. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  41052. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  41053. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41054. * 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).
  41055. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41056. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41057. */
  41058. MeshBuilder.CreateTorus = function (name, options, scene) {
  41059. var torus = new BABYLON.Mesh(name, scene);
  41060. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41061. torus.sideOrientation = options.sideOrientation;
  41062. var vertexData = BABYLON.VertexData.CreateTorus(options);
  41063. vertexData.applyToMesh(torus, options.updatable);
  41064. return torus;
  41065. };
  41066. /**
  41067. * Creates a torus knot mesh.
  41068. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  41069. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  41070. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  41071. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  41072. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  41073. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41074. * 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).
  41075. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41076. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41077. */
  41078. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  41079. var torusKnot = new BABYLON.Mesh(name, scene);
  41080. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41081. torusKnot.sideOrientation = options.sideOrientation;
  41082. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  41083. vertexData.applyToMesh(torusKnot, options.updatable);
  41084. return torusKnot;
  41085. };
  41086. /**
  41087. * Creates a line system mesh.
  41088. * A line system is a pool of many lines gathered in a single mesh.
  41089. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  41090. * 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.
  41091. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  41092. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  41093. * 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
  41094. * 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
  41095. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  41096. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41097. */
  41098. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  41099. var instance = options.instance;
  41100. var lines = options.lines;
  41101. if (instance) {
  41102. var positionFunction = function (positions) {
  41103. var i = 0;
  41104. for (var l = 0; l < lines.length; l++) {
  41105. var points = lines[l];
  41106. for (var p = 0; p < points.length; p++) {
  41107. positions[i] = points[p].x;
  41108. positions[i + 1] = points[p].y;
  41109. positions[i + 2] = points[p].z;
  41110. i += 3;
  41111. }
  41112. }
  41113. };
  41114. instance.updateMeshPositions(positionFunction, false);
  41115. return instance;
  41116. }
  41117. // line system creation
  41118. var lineSystem = new BABYLON.LinesMesh(name, scene);
  41119. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  41120. vertexData.applyToMesh(lineSystem, options.updatable);
  41121. return lineSystem;
  41122. };
  41123. /**
  41124. * Creates a line mesh.
  41125. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  41126. * 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.
  41127. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  41128. * The parameter `points` is an array successive Vector3.
  41129. * 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
  41130. * When updating an instance, remember that only point positions can change, not the number of points.
  41131. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41132. */
  41133. MeshBuilder.CreateLines = function (name, options, scene) {
  41134. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  41135. return lines;
  41136. };
  41137. /**
  41138. * Creates a dashed line mesh.
  41139. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  41140. * 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.
  41141. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  41142. * The parameter `points` is an array successive Vector3.
  41143. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  41144. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  41145. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  41146. * 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
  41147. * When updating an instance, remember that only point positions can change, not the number of points.
  41148. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41149. */
  41150. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  41151. var points = options.points;
  41152. var instance = options.instance;
  41153. var gapSize = options.gapSize;
  41154. var dashNb = options.dashNb;
  41155. var dashSize = options.dashSize;
  41156. if (instance) {
  41157. var positionFunction = function (positions) {
  41158. var curvect = BABYLON.Vector3.Zero();
  41159. var nbSeg = positions.length / 6;
  41160. var lg = 0;
  41161. var nb = 0;
  41162. var shft = 0;
  41163. var dashshft = 0;
  41164. var curshft = 0;
  41165. var p = 0;
  41166. var i = 0;
  41167. var j = 0;
  41168. for (i = 0; i < points.length - 1; i++) {
  41169. points[i + 1].subtractToRef(points[i], curvect);
  41170. lg += curvect.length();
  41171. }
  41172. shft = lg / nbSeg;
  41173. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  41174. for (i = 0; i < points.length - 1; i++) {
  41175. points[i + 1].subtractToRef(points[i], curvect);
  41176. nb = Math.floor(curvect.length() / shft);
  41177. curvect.normalize();
  41178. j = 0;
  41179. while (j < nb && p < positions.length) {
  41180. curshft = shft * j;
  41181. positions[p] = points[i].x + curshft * curvect.x;
  41182. positions[p + 1] = points[i].y + curshft * curvect.y;
  41183. positions[p + 2] = points[i].z + curshft * curvect.z;
  41184. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  41185. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  41186. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  41187. p += 6;
  41188. j++;
  41189. }
  41190. }
  41191. while (p < positions.length) {
  41192. positions[p] = points[i].x;
  41193. positions[p + 1] = points[i].y;
  41194. positions[p + 2] = points[i].z;
  41195. p += 3;
  41196. }
  41197. };
  41198. instance.updateMeshPositions(positionFunction, false);
  41199. return instance;
  41200. }
  41201. // dashed lines creation
  41202. var dashedLines = new BABYLON.LinesMesh(name, scene);
  41203. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  41204. vertexData.applyToMesh(dashedLines, options.updatable);
  41205. dashedLines.dashSize = dashSize;
  41206. dashedLines.gapSize = gapSize;
  41207. return dashedLines;
  41208. };
  41209. /**
  41210. * Creates an extruded shape mesh.
  41211. * 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.
  41212. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  41213. *
  41214. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  41215. * 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
  41216. * extruded along the Z axis.
  41217. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  41218. * 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.
  41219. * The parameter `scale` (float, default 1) is the value to scale the shape.
  41220. * 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
  41221. * 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
  41222. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  41223. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41224. * 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).
  41225. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41226. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  41227. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41228. */
  41229. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  41230. var path = options.path;
  41231. var shape = options.shape;
  41232. var scale = options.scale || 1;
  41233. var rotation = options.rotation || 0;
  41234. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  41235. var updatable = options.updatable;
  41236. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41237. var instance = options.instance;
  41238. var invertUV = options.invertUV || false;
  41239. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  41240. };
  41241. /**
  41242. * Creates an custom extruded shape mesh.
  41243. * 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.
  41244. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  41245. *
  41246. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  41247. * 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
  41248. * extruded along the Z axis.
  41249. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  41250. * 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
  41251. * and the distance of this point from the begining of the path :
  41252. * ```javascript
  41253. * var rotationFunction = function(i, distance) {
  41254. * // do things
  41255. * return rotationValue; }
  41256. * ```
  41257. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  41258. * 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
  41259. * and the distance of this point from the begining of the path :
  41260. * ```javascript
  41261. * var scaleFunction = function(i, distance) {
  41262. * // do things
  41263. * return scaleValue;}
  41264. * ```
  41265. * It must returns a float value that will be the scale value applied to the shape on each path point.
  41266. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  41267. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  41268. * 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
  41269. * 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
  41270. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  41271. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41272. * 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).
  41273. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41274. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  41275. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41276. */
  41277. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  41278. var path = options.path;
  41279. var shape = options.shape;
  41280. var scaleFunction = options.scaleFunction || (function () { return 1; });
  41281. var rotationFunction = options.rotationFunction || (function () { return 0; });
  41282. var ribbonCloseArray = options.ribbonCloseArray || false;
  41283. var ribbonClosePath = options.ribbonClosePath || false;
  41284. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  41285. var updatable = options.updatable;
  41286. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41287. var instance = options.instance;
  41288. var invertUV = options.invertUV || false;
  41289. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  41290. };
  41291. /**
  41292. * Creates lathe mesh.
  41293. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  41294. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  41295. *
  41296. * 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
  41297. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  41298. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  41299. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  41300. * 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.
  41301. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  41302. * 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
  41303. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41304. * 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).
  41305. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41306. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  41307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41308. */
  41309. MeshBuilder.CreateLathe = function (name, options, scene) {
  41310. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  41311. var closed = (options.closed === undefined) ? true : options.closed;
  41312. var shape = options.shape;
  41313. var radius = options.radius || 1;
  41314. var tessellation = options.tessellation || 64;
  41315. var updatable = options.updatable;
  41316. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41317. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  41318. var pi2 = Math.PI * 2;
  41319. var paths = new Array();
  41320. var invertUV = options.invertUV || false;
  41321. var i = 0;
  41322. var p = 0;
  41323. var step = pi2 / tessellation * arc;
  41324. var rotated;
  41325. var path = new Array();
  41326. ;
  41327. for (i = 0; i <= tessellation; i++) {
  41328. var path = [];
  41329. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  41330. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  41331. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  41332. }
  41333. for (p = 0; p < shape.length; p++) {
  41334. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  41335. path.push(rotated);
  41336. }
  41337. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  41338. 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));
  41339. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  41340. }
  41341. paths.push(path);
  41342. }
  41343. // lathe ribbon
  41344. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  41345. return lathe;
  41346. };
  41347. /**
  41348. * Creates a plane mesh.
  41349. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  41350. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  41351. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  41352. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  41353. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41354. * 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).
  41355. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41356. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41357. */
  41358. MeshBuilder.CreatePlane = function (name, options, scene) {
  41359. var plane = new BABYLON.Mesh(name, scene);
  41360. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41361. plane.sideOrientation = options.sideOrientation;
  41362. var vertexData = BABYLON.VertexData.CreatePlane(options);
  41363. vertexData.applyToMesh(plane, options.updatable);
  41364. if (options.sourcePlane) {
  41365. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  41366. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  41367. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  41368. plane.rotate(vectorProduct, product);
  41369. }
  41370. return plane;
  41371. };
  41372. /**
  41373. * Creates a ground mesh.
  41374. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  41375. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  41376. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  41377. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41378. */
  41379. MeshBuilder.CreateGround = function (name, options, scene) {
  41380. var ground = new BABYLON.GroundMesh(name, scene);
  41381. ground._setReady(false);
  41382. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  41383. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  41384. ground._width = options.width || 1;
  41385. ground._height = options.height || 1;
  41386. ground._maxX = ground._width / 2;
  41387. ground._maxZ = ground._height / 2;
  41388. ground._minX = -ground._maxX;
  41389. ground._minZ = -ground._maxZ;
  41390. var vertexData = BABYLON.VertexData.CreateGround(options);
  41391. vertexData.applyToMesh(ground, options.updatable);
  41392. ground._setReady(true);
  41393. return ground;
  41394. };
  41395. /**
  41396. * Creates a tiled ground mesh.
  41397. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  41398. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  41399. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  41400. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  41401. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  41402. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  41403. * numbers of subdivisions on the ground width and height of each tile.
  41404. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41405. */
  41406. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  41407. var tiledGround = new BABYLON.Mesh(name, scene);
  41408. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  41409. vertexData.applyToMesh(tiledGround, options.updatable);
  41410. return tiledGround;
  41411. };
  41412. /**
  41413. * Creates a ground mesh from a height map.
  41414. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  41415. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  41416. * The parameter `url` sets the URL of the height map image resource.
  41417. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  41418. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  41419. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  41420. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  41421. * 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.
  41422. * 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).
  41423. * This function is passed the newly built mesh :
  41424. * ```javascript
  41425. * function(mesh) { // do things
  41426. * return; }
  41427. * ```
  41428. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41429. */
  41430. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  41431. var width = options.width || 10.0;
  41432. var height = options.height || 10.0;
  41433. var subdivisions = options.subdivisions || 1 | 0;
  41434. var minHeight = options.minHeight || 0.0;
  41435. var maxHeight = options.maxHeight || 10.0;
  41436. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  41437. var updatable = options.updatable;
  41438. var onReady = options.onReady;
  41439. var ground = new BABYLON.GroundMesh(name, scene);
  41440. ground._subdivisionsX = subdivisions;
  41441. ground._subdivisionsY = subdivisions;
  41442. ground._width = width;
  41443. ground._height = height;
  41444. ground._maxX = ground._width / 2.0;
  41445. ground._maxZ = ground._height / 2.0;
  41446. ground._minX = -ground._maxX;
  41447. ground._minZ = -ground._maxZ;
  41448. ground._setReady(false);
  41449. var onload = function (img) {
  41450. // Getting height map data
  41451. var canvas = document.createElement("canvas");
  41452. var context = canvas.getContext("2d");
  41453. var bufferWidth = img.width;
  41454. var bufferHeight = img.height;
  41455. canvas.width = bufferWidth;
  41456. canvas.height = bufferHeight;
  41457. context.drawImage(img, 0, 0);
  41458. // Create VertexData from map data
  41459. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  41460. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  41461. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  41462. width: width, height: height,
  41463. subdivisions: subdivisions,
  41464. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  41465. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  41466. });
  41467. vertexData.applyToMesh(ground, updatable);
  41468. ground._setReady(true);
  41469. //execute ready callback, if set
  41470. if (onReady) {
  41471. onReady(ground);
  41472. }
  41473. };
  41474. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  41475. return ground;
  41476. };
  41477. /**
  41478. * Creates a polygon mesh.
  41479. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  41480. * 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.
  41481. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41482. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41483. * 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).
  41484. * Remember you can only change the shape positions, not their number when updating a polygon.
  41485. */
  41486. MeshBuilder.CreatePolygon = function (name, options, scene) {
  41487. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41488. var shape = options.shape;
  41489. var holes = options.holes || [];
  41490. var depth = options.depth || 0;
  41491. var contours = [];
  41492. var hole = [];
  41493. for (var i = 0; i < shape.length; i++) {
  41494. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  41495. }
  41496. var epsilon = 0.00000001;
  41497. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  41498. contours.pop();
  41499. }
  41500. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  41501. for (var hNb = 0; hNb < holes.length; hNb++) {
  41502. hole = [];
  41503. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  41504. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  41505. }
  41506. polygonTriangulation.addHole(hole);
  41507. }
  41508. var polygon = polygonTriangulation.build(options.updatable, depth);
  41509. polygon.sideOrientation = options.sideOrientation;
  41510. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  41511. vertexData.applyToMesh(polygon, options.updatable);
  41512. return polygon;
  41513. };
  41514. ;
  41515. /**
  41516. * Creates an extruded polygon mesh, with depth in the Y direction.
  41517. * 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).
  41518. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  41519. */
  41520. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  41521. return MeshBuilder.CreatePolygon(name, options, scene);
  41522. };
  41523. ;
  41524. /**
  41525. * Creates a tube mesh.
  41526. * 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.
  41527. *
  41528. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  41529. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  41530. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  41531. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  41532. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  41533. * 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.
  41534. * It must return a radius value (positive float) :
  41535. * ```javascript
  41536. * var radiusFunction = function(i, distance) {
  41537. * // do things
  41538. * return radius; }
  41539. * ```
  41540. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  41541. * 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
  41542. * 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
  41543. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41544. * 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).
  41545. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41546. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  41547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41548. */
  41549. MeshBuilder.CreateTube = function (name, options, scene) {
  41550. var path = options.path;
  41551. var radius = options.radius || 1.0;
  41552. var tessellation = options.tessellation || 64 | 0;
  41553. var radiusFunction = options.radiusFunction;
  41554. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  41555. var invertUV = options.invertUV || false;
  41556. var updatable = options.updatable;
  41557. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41558. var instance = options.instance;
  41559. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  41560. // tube geometry
  41561. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  41562. var tangents = path3D.getTangents();
  41563. var normals = path3D.getNormals();
  41564. var distances = path3D.getDistances();
  41565. var pi2 = Math.PI * 2;
  41566. var step = pi2 / tessellation * arc;
  41567. var returnRadius = function () { return radius; };
  41568. var radiusFunctionFinal = radiusFunction || returnRadius;
  41569. var circlePath;
  41570. var rad;
  41571. var normal;
  41572. var rotated;
  41573. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  41574. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  41575. for (var i = 0; i < path.length; i++) {
  41576. rad = radiusFunctionFinal(i, distances[i]); // current radius
  41577. circlePath = Array(); // current circle array
  41578. normal = normals[i]; // current normal
  41579. for (var t = 0; t < tessellation; t++) {
  41580. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  41581. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  41582. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  41583. rotated.scaleInPlace(rad).addInPlace(path[i]);
  41584. circlePath[t] = rotated;
  41585. }
  41586. circlePaths[index] = circlePath;
  41587. index++;
  41588. }
  41589. // cap
  41590. var capPath = function (nbPoints, pathIndex) {
  41591. var pointCap = Array();
  41592. for (var i = 0; i < nbPoints; i++) {
  41593. pointCap.push(path[pathIndex]);
  41594. }
  41595. return pointCap;
  41596. };
  41597. switch (cap) {
  41598. case BABYLON.Mesh.NO_CAP:
  41599. break;
  41600. case BABYLON.Mesh.CAP_START:
  41601. circlePaths[0] = capPath(tessellation, 0);
  41602. circlePaths[1] = circlePaths[2].slice(0);
  41603. break;
  41604. case BABYLON.Mesh.CAP_END:
  41605. circlePaths[index] = circlePaths[index - 1].slice(0);
  41606. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  41607. break;
  41608. case BABYLON.Mesh.CAP_ALL:
  41609. circlePaths[0] = capPath(tessellation, 0);
  41610. circlePaths[1] = circlePaths[2].slice(0);
  41611. circlePaths[index] = circlePaths[index - 1].slice(0);
  41612. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  41613. break;
  41614. default:
  41615. break;
  41616. }
  41617. return circlePaths;
  41618. };
  41619. var path3D;
  41620. var pathArray;
  41621. if (instance) {
  41622. var arc = options.arc || instance.arc;
  41623. path3D = (instance.path3D).update(path);
  41624. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  41625. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  41626. instance.path3D = path3D;
  41627. instance.pathArray = pathArray;
  41628. instance.arc = arc;
  41629. return instance;
  41630. }
  41631. // tube creation
  41632. path3D = new BABYLON.Path3D(path);
  41633. var newPathArray = new Array();
  41634. cap = (cap < 0 || cap > 3) ? 0 : cap;
  41635. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  41636. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  41637. tube.pathArray = pathArray;
  41638. tube.path3D = path3D;
  41639. tube.tessellation = tessellation;
  41640. tube.cap = cap;
  41641. tube.arc = options.arc;
  41642. return tube;
  41643. };
  41644. /**
  41645. * Creates a polyhedron mesh.
  41646. *
  41647. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  41648. * 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
  41649. * to choose the wanted type.
  41650. * The parameter `size` (positive float, default 1) sets the polygon size.
  41651. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  41652. * 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`.
  41653. * 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
  41654. * 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)`).
  41655. * 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
  41656. * 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.
  41657. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41658. * 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).
  41659. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41660. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41661. */
  41662. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  41663. var polyhedron = new BABYLON.Mesh(name, scene);
  41664. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41665. polyhedron.sideOrientation = options.sideOrientation;
  41666. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  41667. vertexData.applyToMesh(polyhedron, options.updatable);
  41668. return polyhedron;
  41669. };
  41670. /**
  41671. * Creates a decal mesh.
  41672. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  41673. * 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.
  41674. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  41675. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  41676. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  41677. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  41678. */
  41679. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  41680. var indices = sourceMesh.getIndices();
  41681. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41682. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41683. var position = options.position || BABYLON.Vector3.Zero();
  41684. var normal = options.normal || BABYLON.Vector3.Up();
  41685. var size = options.size || BABYLON.Vector3.One();
  41686. var angle = options.angle || 0;
  41687. // Getting correct rotation
  41688. if (!normal) {
  41689. var target = new BABYLON.Vector3(0, 0, 1);
  41690. var camera = sourceMesh.getScene().activeCamera;
  41691. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  41692. normal = camera.globalPosition.subtract(cameraWorldTarget);
  41693. }
  41694. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  41695. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  41696. var pitch = Math.atan2(normal.y, len);
  41697. // Matrix
  41698. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  41699. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  41700. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  41701. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  41702. var vertexData = new BABYLON.VertexData();
  41703. vertexData.indices = [];
  41704. vertexData.positions = [];
  41705. vertexData.normals = [];
  41706. vertexData.uvs = [];
  41707. var currentVertexDataIndex = 0;
  41708. var extractDecalVector3 = function (indexId) {
  41709. var vertexId = indices[indexId];
  41710. var result = new BABYLON.PositionNormalVertex();
  41711. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  41712. // Send vector to decal local world
  41713. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  41714. // Get normal
  41715. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  41716. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  41717. return result;
  41718. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  41719. var clip = function (vertices, axis) {
  41720. if (vertices.length === 0) {
  41721. return vertices;
  41722. }
  41723. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  41724. var clipVertices = function (v0, v1) {
  41725. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  41726. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  41727. };
  41728. var result = new Array();
  41729. for (var index = 0; index < vertices.length; index += 3) {
  41730. var v1Out;
  41731. var v2Out;
  41732. var v3Out;
  41733. var total = 0;
  41734. var nV1, nV2, nV3, nV4;
  41735. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  41736. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  41737. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  41738. v1Out = d1 > 0;
  41739. v2Out = d2 > 0;
  41740. v3Out = d3 > 0;
  41741. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  41742. switch (total) {
  41743. case 0:
  41744. result.push(vertices[index]);
  41745. result.push(vertices[index + 1]);
  41746. result.push(vertices[index + 2]);
  41747. break;
  41748. case 1:
  41749. if (v1Out) {
  41750. nV1 = vertices[index + 1];
  41751. nV2 = vertices[index + 2];
  41752. nV3 = clipVertices(vertices[index], nV1);
  41753. nV4 = clipVertices(vertices[index], nV2);
  41754. }
  41755. if (v2Out) {
  41756. nV1 = vertices[index];
  41757. nV2 = vertices[index + 2];
  41758. nV3 = clipVertices(vertices[index + 1], nV1);
  41759. nV4 = clipVertices(vertices[index + 1], nV2);
  41760. result.push(nV3);
  41761. result.push(nV2.clone());
  41762. result.push(nV1.clone());
  41763. result.push(nV2.clone());
  41764. result.push(nV3.clone());
  41765. result.push(nV4);
  41766. break;
  41767. }
  41768. if (v3Out) {
  41769. nV1 = vertices[index];
  41770. nV2 = vertices[index + 1];
  41771. nV3 = clipVertices(vertices[index + 2], nV1);
  41772. nV4 = clipVertices(vertices[index + 2], nV2);
  41773. }
  41774. result.push(nV1.clone());
  41775. result.push(nV2.clone());
  41776. result.push(nV3);
  41777. result.push(nV4);
  41778. result.push(nV3.clone());
  41779. result.push(nV2.clone());
  41780. break;
  41781. case 2:
  41782. if (!v1Out) {
  41783. nV1 = vertices[index].clone();
  41784. nV2 = clipVertices(nV1, vertices[index + 1]);
  41785. nV3 = clipVertices(nV1, vertices[index + 2]);
  41786. result.push(nV1);
  41787. result.push(nV2);
  41788. result.push(nV3);
  41789. }
  41790. if (!v2Out) {
  41791. nV1 = vertices[index + 1].clone();
  41792. nV2 = clipVertices(nV1, vertices[index + 2]);
  41793. nV3 = clipVertices(nV1, vertices[index]);
  41794. result.push(nV1);
  41795. result.push(nV2);
  41796. result.push(nV3);
  41797. }
  41798. if (!v3Out) {
  41799. nV1 = vertices[index + 2].clone();
  41800. nV2 = clipVertices(nV1, vertices[index]);
  41801. nV3 = clipVertices(nV1, vertices[index + 1]);
  41802. result.push(nV1);
  41803. result.push(nV2);
  41804. result.push(nV3);
  41805. }
  41806. break;
  41807. case 3:
  41808. break;
  41809. }
  41810. }
  41811. return result;
  41812. };
  41813. for (var index = 0; index < indices.length; index += 3) {
  41814. var faceVertices = new Array();
  41815. faceVertices.push(extractDecalVector3(index));
  41816. faceVertices.push(extractDecalVector3(index + 1));
  41817. faceVertices.push(extractDecalVector3(index + 2));
  41818. // Clip
  41819. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  41820. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  41821. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  41822. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  41823. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  41824. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  41825. if (faceVertices.length === 0) {
  41826. continue;
  41827. }
  41828. // Add UVs and get back to world
  41829. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  41830. var vertex = faceVertices[vIndex];
  41831. //TODO check for Int32Array | Uint32Array | Uint16Array
  41832. vertexData.indices.push(currentVertexDataIndex);
  41833. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  41834. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  41835. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  41836. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  41837. currentVertexDataIndex++;
  41838. }
  41839. }
  41840. // Return mesh
  41841. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  41842. vertexData.applyToMesh(decal);
  41843. decal.position = position.clone();
  41844. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  41845. return decal;
  41846. };
  41847. // Privates
  41848. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  41849. // extrusion geometry
  41850. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  41851. var tangents = path3D.getTangents();
  41852. var normals = path3D.getNormals();
  41853. var binormals = path3D.getBinormals();
  41854. var distances = path3D.getDistances();
  41855. var angle = 0;
  41856. var returnScale = function () { return scale; };
  41857. var returnRotation = function () { return rotation; };
  41858. var rotate = custom ? rotateFunction : returnRotation;
  41859. var scl = custom ? scaleFunction : returnScale;
  41860. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  41861. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  41862. for (var i = 0; i < curve.length; i++) {
  41863. var shapePath = new Array();
  41864. var angleStep = rotate(i, distances[i]);
  41865. var scaleRatio = scl(i, distances[i]);
  41866. for (var p = 0; p < shape.length; p++) {
  41867. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  41868. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  41869. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  41870. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  41871. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  41872. shapePath[p] = rotated;
  41873. }
  41874. shapePaths[index] = shapePath;
  41875. angle += angleStep;
  41876. index++;
  41877. }
  41878. // cap
  41879. var capPath = function (shapePath) {
  41880. var pointCap = Array();
  41881. var barycenter = BABYLON.Vector3.Zero();
  41882. var i;
  41883. for (i = 0; i < shapePath.length; i++) {
  41884. barycenter.addInPlace(shapePath[i]);
  41885. }
  41886. barycenter.scaleInPlace(1.0 / shapePath.length);
  41887. for (i = 0; i < shapePath.length; i++) {
  41888. pointCap.push(barycenter);
  41889. }
  41890. return pointCap;
  41891. };
  41892. switch (cap) {
  41893. case BABYLON.Mesh.NO_CAP:
  41894. break;
  41895. case BABYLON.Mesh.CAP_START:
  41896. shapePaths[0] = capPath(shapePaths[2]);
  41897. shapePaths[1] = shapePaths[2];
  41898. break;
  41899. case BABYLON.Mesh.CAP_END:
  41900. shapePaths[index] = shapePaths[index - 1];
  41901. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  41902. break;
  41903. case BABYLON.Mesh.CAP_ALL:
  41904. shapePaths[0] = capPath(shapePaths[2]);
  41905. shapePaths[1] = shapePaths[2];
  41906. shapePaths[index] = shapePaths[index - 1];
  41907. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  41908. break;
  41909. default:
  41910. break;
  41911. }
  41912. return shapePaths;
  41913. };
  41914. var path3D;
  41915. var pathArray;
  41916. if (instance) {
  41917. path3D = (instance.path3D).update(curve);
  41918. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  41919. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  41920. return instance;
  41921. }
  41922. // extruded shape creation
  41923. path3D = new BABYLON.Path3D(curve);
  41924. var newShapePaths = new Array();
  41925. cap = (cap < 0 || cap > 3) ? 0 : cap;
  41926. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  41927. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  41928. extrudedGeneric.pathArray = pathArray;
  41929. extrudedGeneric.path3D = path3D;
  41930. extrudedGeneric.cap = cap;
  41931. return extrudedGeneric;
  41932. };
  41933. return MeshBuilder;
  41934. }());
  41935. BABYLON.MeshBuilder = MeshBuilder;
  41936. })(BABYLON || (BABYLON = {}));
  41937. //# sourceMappingURL=babylon.meshBuilder.js.map
  41938. var BABYLON;
  41939. (function (BABYLON) {
  41940. var AudioEngine = (function () {
  41941. function AudioEngine() {
  41942. this._audioContext = null;
  41943. this._audioContextInitialized = false;
  41944. this.canUseWebAudio = false;
  41945. this.WarnedWebAudioUnsupported = false;
  41946. this.unlocked = false;
  41947. this.isMP3supported = false;
  41948. this.isOGGsupported = false;
  41949. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  41950. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  41951. this.canUseWebAudio = true;
  41952. }
  41953. var audioElem = document.createElement('audio');
  41954. try {
  41955. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  41956. this.isMP3supported = true;
  41957. }
  41958. }
  41959. catch (e) {
  41960. // protect error during capability check.
  41961. }
  41962. try {
  41963. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  41964. this.isOGGsupported = true;
  41965. }
  41966. }
  41967. catch (e) {
  41968. // protect error during capability check.
  41969. }
  41970. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  41971. this._unlockiOSaudio();
  41972. }
  41973. else {
  41974. this.unlocked = true;
  41975. }
  41976. }
  41977. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  41978. get: function () {
  41979. if (!this._audioContextInitialized) {
  41980. this._initializeAudioContext();
  41981. }
  41982. return this._audioContext;
  41983. },
  41984. enumerable: true,
  41985. configurable: true
  41986. });
  41987. AudioEngine.prototype._unlockiOSaudio = function () {
  41988. var _this = this;
  41989. var unlockaudio = function () {
  41990. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  41991. var source = _this.audioContext.createBufferSource();
  41992. source.buffer = buffer;
  41993. source.connect(_this.audioContext.destination);
  41994. source.start(0);
  41995. setTimeout(function () {
  41996. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  41997. _this.unlocked = true;
  41998. window.removeEventListener('touchend', unlockaudio, false);
  41999. if (_this.onAudioUnlocked) {
  42000. _this.onAudioUnlocked();
  42001. }
  42002. }
  42003. }, 0);
  42004. };
  42005. window.addEventListener('touchend', unlockaudio, false);
  42006. };
  42007. AudioEngine.prototype._initializeAudioContext = function () {
  42008. try {
  42009. if (this.canUseWebAudio) {
  42010. this._audioContext = new AudioContext();
  42011. // create a global volume gain node
  42012. this.masterGain = this._audioContext.createGain();
  42013. this.masterGain.gain.value = 1;
  42014. this.masterGain.connect(this._audioContext.destination);
  42015. this._audioContextInitialized = true;
  42016. }
  42017. }
  42018. catch (e) {
  42019. this.canUseWebAudio = false;
  42020. BABYLON.Tools.Error("Web Audio: " + e.message);
  42021. }
  42022. };
  42023. AudioEngine.prototype.dispose = function () {
  42024. if (this.canUseWebAudio && this._audioContextInitialized) {
  42025. if (this._connectedAnalyser) {
  42026. this._connectedAnalyser.stopDebugCanvas();
  42027. this._connectedAnalyser.dispose();
  42028. this.masterGain.disconnect();
  42029. this.masterGain.connect(this._audioContext.destination);
  42030. this._connectedAnalyser = null;
  42031. }
  42032. this.masterGain.gain.value = 1;
  42033. }
  42034. this.WarnedWebAudioUnsupported = false;
  42035. };
  42036. AudioEngine.prototype.getGlobalVolume = function () {
  42037. if (this.canUseWebAudio && this._audioContextInitialized) {
  42038. return this.masterGain.gain.value;
  42039. }
  42040. else {
  42041. return -1;
  42042. }
  42043. };
  42044. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  42045. if (this.canUseWebAudio && this._audioContextInitialized) {
  42046. this.masterGain.gain.value = newVolume;
  42047. }
  42048. };
  42049. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  42050. if (this._connectedAnalyser) {
  42051. this._connectedAnalyser.stopDebugCanvas();
  42052. }
  42053. if (this.canUseWebAudio && this._audioContextInitialized) {
  42054. this._connectedAnalyser = analyser;
  42055. this.masterGain.disconnect();
  42056. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  42057. }
  42058. };
  42059. return AudioEngine;
  42060. }());
  42061. BABYLON.AudioEngine = AudioEngine;
  42062. })(BABYLON || (BABYLON = {}));
  42063. //# sourceMappingURL=babylon.audioEngine.js.map
  42064. var BABYLON;
  42065. (function (BABYLON) {
  42066. var Sound = (function () {
  42067. /**
  42068. * Create a sound and attach it to a scene
  42069. * @param name Name of your sound
  42070. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  42071. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  42072. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  42073. */
  42074. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  42075. var _this = this;
  42076. this.autoplay = false;
  42077. this.loop = false;
  42078. this.useCustomAttenuation = false;
  42079. this.spatialSound = false;
  42080. this.refDistance = 1;
  42081. this.rolloffFactor = 1;
  42082. this.maxDistance = 100;
  42083. this.distanceModel = "linear";
  42084. this._panningModel = "equalpower";
  42085. this._playbackRate = 1;
  42086. this._streaming = false;
  42087. this._startTime = 0;
  42088. this._startOffset = 0;
  42089. this._position = BABYLON.Vector3.Zero();
  42090. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  42091. this._volume = 1;
  42092. this._isLoaded = false;
  42093. this._isReadyToPlay = false;
  42094. this.isPlaying = false;
  42095. this.isPaused = false;
  42096. this._isDirectional = false;
  42097. // Used if you'd like to create a directional sound.
  42098. // If not set, the sound will be omnidirectional
  42099. this._coneInnerAngle = 360;
  42100. this._coneOuterAngle = 360;
  42101. this._coneOuterGain = 0;
  42102. this._isOutputConnected = false;
  42103. this._urlType = "Unknown";
  42104. this.name = name;
  42105. this._scene = scene;
  42106. this._readyToPlayCallback = readyToPlayCallback;
  42107. // Default custom attenuation function is a linear attenuation
  42108. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  42109. if (currentDistance < maxDistance) {
  42110. return currentVolume * (1 - currentDistance / maxDistance);
  42111. }
  42112. else {
  42113. return 0;
  42114. }
  42115. };
  42116. if (options) {
  42117. this.autoplay = options.autoplay || false;
  42118. this.loop = options.loop || false;
  42119. // if volume === 0, we need another way to check this option
  42120. if (options.volume !== undefined) {
  42121. this._volume = options.volume;
  42122. }
  42123. this.spatialSound = options.spatialSound || false;
  42124. this.maxDistance = options.maxDistance || 100;
  42125. this.useCustomAttenuation = options.useCustomAttenuation || false;
  42126. this.rolloffFactor = options.rolloffFactor || 1;
  42127. this.refDistance = options.refDistance || 1;
  42128. this.distanceModel = options.distanceModel || "linear";
  42129. this._playbackRate = options.playbackRate || 1;
  42130. this._streaming = options.streaming || false;
  42131. }
  42132. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42133. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  42134. this._soundGain.gain.value = this._volume;
  42135. this._inputAudioNode = this._soundGain;
  42136. this._ouputAudioNode = this._soundGain;
  42137. if (this.spatialSound) {
  42138. this._createSpatialParameters();
  42139. }
  42140. this._scene.mainSoundTrack.AddSound(this);
  42141. var validParameter = true;
  42142. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  42143. if (urlOrArrayBuffer) {
  42144. if (typeof (urlOrArrayBuffer) === "string")
  42145. this._urlType = "String";
  42146. if (Array.isArray(urlOrArrayBuffer))
  42147. this._urlType = "Array";
  42148. if (urlOrArrayBuffer instanceof ArrayBuffer)
  42149. this._urlType = "ArrayBuffer";
  42150. var urls = [];
  42151. var codecSupportedFound = false;
  42152. switch (this._urlType) {
  42153. case "ArrayBuffer":
  42154. if (urlOrArrayBuffer.byteLength > 0) {
  42155. codecSupportedFound = true;
  42156. this._soundLoaded(urlOrArrayBuffer);
  42157. }
  42158. break;
  42159. case "String":
  42160. urls.push(urlOrArrayBuffer);
  42161. case "Array":
  42162. if (urls.length === 0)
  42163. urls = urlOrArrayBuffer;
  42164. // If we found a supported format, we load it immediately and stop the loop
  42165. for (var i = 0; i < urls.length; i++) {
  42166. var url = urls[i];
  42167. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  42168. codecSupportedFound = true;
  42169. }
  42170. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  42171. codecSupportedFound = true;
  42172. }
  42173. if (url.indexOf(".wav", url.length - 4) !== -1) {
  42174. codecSupportedFound = true;
  42175. }
  42176. if (codecSupportedFound) {
  42177. // Loading sound using XHR2
  42178. if (!this._streaming) {
  42179. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  42180. }
  42181. else {
  42182. this._htmlAudioElement = new Audio(url);
  42183. this._htmlAudioElement.controls = false;
  42184. this._htmlAudioElement.loop = this.loop;
  42185. this._htmlAudioElement.crossOrigin = "anonymous";
  42186. this._htmlAudioElement.preload = "auto";
  42187. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  42188. _this._isReadyToPlay = true;
  42189. if (_this.autoplay) {
  42190. _this.play();
  42191. }
  42192. if (_this._readyToPlayCallback) {
  42193. _this._readyToPlayCallback();
  42194. }
  42195. });
  42196. document.body.appendChild(this._htmlAudioElement);
  42197. }
  42198. break;
  42199. }
  42200. }
  42201. break;
  42202. default:
  42203. validParameter = false;
  42204. break;
  42205. }
  42206. if (!validParameter) {
  42207. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  42208. }
  42209. else {
  42210. if (!codecSupportedFound) {
  42211. this._isReadyToPlay = true;
  42212. // Simulating a ready to play event to avoid breaking code path
  42213. if (this._readyToPlayCallback) {
  42214. window.setTimeout(function () {
  42215. _this._readyToPlayCallback();
  42216. }, 1000);
  42217. }
  42218. }
  42219. }
  42220. }
  42221. }
  42222. else {
  42223. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  42224. this._scene.mainSoundTrack.AddSound(this);
  42225. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  42226. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  42227. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  42228. }
  42229. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  42230. if (this._readyToPlayCallback) {
  42231. window.setTimeout(function () {
  42232. _this._readyToPlayCallback();
  42233. }, 1000);
  42234. }
  42235. }
  42236. }
  42237. Sound.prototype.dispose = function () {
  42238. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  42239. if (this.isPlaying) {
  42240. this.stop();
  42241. }
  42242. this._isReadyToPlay = false;
  42243. if (this.soundTrackId === -1) {
  42244. this._scene.mainSoundTrack.RemoveSound(this);
  42245. }
  42246. else {
  42247. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  42248. }
  42249. if (this._soundGain) {
  42250. this._soundGain.disconnect();
  42251. this._soundGain = null;
  42252. }
  42253. if (this._soundPanner) {
  42254. this._soundPanner.disconnect();
  42255. this._soundPanner = null;
  42256. }
  42257. if (this._soundSource) {
  42258. this._soundSource.disconnect();
  42259. this._soundSource = null;
  42260. }
  42261. this._audioBuffer = null;
  42262. if (this._htmlAudioElement) {
  42263. this._htmlAudioElement.pause();
  42264. this._htmlAudioElement.src = "";
  42265. document.body.removeChild(this._htmlAudioElement);
  42266. }
  42267. if (this._connectedMesh) {
  42268. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42269. this._connectedMesh = null;
  42270. }
  42271. }
  42272. };
  42273. Sound.prototype.isReady = function () {
  42274. return this._isReadyToPlay;
  42275. };
  42276. Sound.prototype._soundLoaded = function (audioData) {
  42277. var _this = this;
  42278. this._isLoaded = true;
  42279. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  42280. _this._audioBuffer = buffer;
  42281. _this._isReadyToPlay = true;
  42282. if (_this.autoplay) {
  42283. _this.play();
  42284. }
  42285. if (_this._readyToPlayCallback) {
  42286. _this._readyToPlayCallback();
  42287. }
  42288. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  42289. };
  42290. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  42291. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42292. this._audioBuffer = audioBuffer;
  42293. this._isReadyToPlay = true;
  42294. }
  42295. };
  42296. Sound.prototype.updateOptions = function (options) {
  42297. if (options) {
  42298. this.loop = options.loop || this.loop;
  42299. this.maxDistance = options.maxDistance || this.maxDistance;
  42300. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  42301. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  42302. this.refDistance = options.refDistance || this.refDistance;
  42303. this.distanceModel = options.distanceModel || this.distanceModel;
  42304. this._playbackRate = options.playbackRate || this._playbackRate;
  42305. this._updateSpatialParameters();
  42306. if (this.isPlaying) {
  42307. if (this._streaming) {
  42308. this._htmlAudioElement.playbackRate = this._playbackRate;
  42309. }
  42310. else {
  42311. this._soundSource.playbackRate.value = this._playbackRate;
  42312. }
  42313. }
  42314. }
  42315. };
  42316. Sound.prototype._createSpatialParameters = function () {
  42317. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42318. if (this._scene.headphone) {
  42319. this._panningModel = "HRTF";
  42320. }
  42321. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  42322. this._updateSpatialParameters();
  42323. this._soundPanner.connect(this._ouputAudioNode);
  42324. this._inputAudioNode = this._soundPanner;
  42325. }
  42326. };
  42327. Sound.prototype._updateSpatialParameters = function () {
  42328. if (this.spatialSound) {
  42329. if (this.useCustomAttenuation) {
  42330. // Tricks to disable in a way embedded Web Audio attenuation
  42331. this._soundPanner.distanceModel = "linear";
  42332. this._soundPanner.maxDistance = Number.MAX_VALUE;
  42333. this._soundPanner.refDistance = 1;
  42334. this._soundPanner.rolloffFactor = 1;
  42335. this._soundPanner.panningModel = this._panningModel;
  42336. }
  42337. else {
  42338. this._soundPanner.distanceModel = this.distanceModel;
  42339. this._soundPanner.maxDistance = this.maxDistance;
  42340. this._soundPanner.refDistance = this.refDistance;
  42341. this._soundPanner.rolloffFactor = this.rolloffFactor;
  42342. this._soundPanner.panningModel = this._panningModel;
  42343. }
  42344. }
  42345. };
  42346. Sound.prototype.switchPanningModelToHRTF = function () {
  42347. this._panningModel = "HRTF";
  42348. this._switchPanningModel();
  42349. };
  42350. Sound.prototype.switchPanningModelToEqualPower = function () {
  42351. this._panningModel = "equalpower";
  42352. this._switchPanningModel();
  42353. };
  42354. Sound.prototype._switchPanningModel = function () {
  42355. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42356. this._soundPanner.panningModel = this._panningModel;
  42357. }
  42358. };
  42359. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  42360. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42361. if (this._isOutputConnected) {
  42362. this._ouputAudioNode.disconnect();
  42363. }
  42364. this._ouputAudioNode.connect(soundTrackAudioNode);
  42365. this._isOutputConnected = true;
  42366. }
  42367. };
  42368. /**
  42369. * Transform this sound into a directional source
  42370. * @param coneInnerAngle Size of the inner cone in degree
  42371. * @param coneOuterAngle Size of the outer cone in degree
  42372. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  42373. */
  42374. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  42375. if (coneOuterAngle < coneInnerAngle) {
  42376. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  42377. return;
  42378. }
  42379. this._coneInnerAngle = coneInnerAngle;
  42380. this._coneOuterAngle = coneOuterAngle;
  42381. this._coneOuterGain = coneOuterGain;
  42382. this._isDirectional = true;
  42383. if (this.isPlaying && this.loop) {
  42384. this.stop();
  42385. this.play();
  42386. }
  42387. };
  42388. Sound.prototype.setPosition = function (newPosition) {
  42389. this._position = newPosition;
  42390. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42391. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42392. }
  42393. };
  42394. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  42395. this._localDirection = newLocalDirection;
  42396. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  42397. this._updateDirection();
  42398. }
  42399. };
  42400. Sound.prototype._updateDirection = function () {
  42401. var mat = this._connectedMesh.getWorldMatrix();
  42402. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  42403. direction.normalize();
  42404. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  42405. };
  42406. Sound.prototype.updateDistanceFromListener = function () {
  42407. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  42408. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  42409. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  42410. }
  42411. };
  42412. Sound.prototype.setAttenuationFunction = function (callback) {
  42413. this._customAttenuationFunction = callback;
  42414. };
  42415. /**
  42416. * Play the sound
  42417. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  42418. * @param offset (optional) Start the sound setting it at a specific time
  42419. */
  42420. Sound.prototype.play = function (time, offset) {
  42421. var _this = this;
  42422. if (this._isReadyToPlay && this._scene.audioEnabled) {
  42423. try {
  42424. if (this._startOffset < 0) {
  42425. time = -this._startOffset;
  42426. this._startOffset = 0;
  42427. }
  42428. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42429. if (!this._soundSource || !this._streamingSource) {
  42430. if (this.spatialSound) {
  42431. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42432. if (this._isDirectional) {
  42433. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  42434. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  42435. this._soundPanner.coneOuterGain = this._coneOuterGain;
  42436. if (this._connectedMesh) {
  42437. this._updateDirection();
  42438. }
  42439. else {
  42440. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  42441. }
  42442. }
  42443. }
  42444. }
  42445. if (this._streaming) {
  42446. if (!this._streamingSource) {
  42447. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  42448. this._htmlAudioElement.onended = function () { _this._onended(); };
  42449. this._htmlAudioElement.playbackRate = this._playbackRate;
  42450. }
  42451. this._streamingSource.disconnect();
  42452. this._streamingSource.connect(this._inputAudioNode);
  42453. this._htmlAudioElement.play();
  42454. }
  42455. else {
  42456. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  42457. this._soundSource.buffer = this._audioBuffer;
  42458. this._soundSource.connect(this._inputAudioNode);
  42459. this._soundSource.loop = this.loop;
  42460. this._soundSource.playbackRate.value = this._playbackRate;
  42461. this._soundSource.onended = function () { _this._onended(); };
  42462. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  42463. }
  42464. this._startTime = startTime;
  42465. this.isPlaying = true;
  42466. this.isPaused = false;
  42467. }
  42468. catch (ex) {
  42469. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  42470. }
  42471. }
  42472. };
  42473. Sound.prototype._onended = function () {
  42474. this.isPlaying = false;
  42475. if (this.onended) {
  42476. this.onended();
  42477. }
  42478. };
  42479. /**
  42480. * Stop the sound
  42481. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  42482. */
  42483. Sound.prototype.stop = function (time) {
  42484. if (this.isPlaying) {
  42485. if (this._streaming) {
  42486. this._htmlAudioElement.pause();
  42487. // Test needed for Firefox or it will generate an Invalid State Error
  42488. if (this._htmlAudioElement.currentTime > 0) {
  42489. this._htmlAudioElement.currentTime = 0;
  42490. }
  42491. }
  42492. else {
  42493. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42494. this._soundSource.stop(stopTime);
  42495. this._soundSource.onended = null;
  42496. if (!this.isPaused) {
  42497. this._startOffset = 0;
  42498. }
  42499. }
  42500. this.isPlaying = false;
  42501. }
  42502. };
  42503. Sound.prototype.pause = function () {
  42504. if (this.isPlaying) {
  42505. this.isPaused = true;
  42506. if (this._streaming) {
  42507. this._htmlAudioElement.pause();
  42508. }
  42509. else {
  42510. this.stop(0);
  42511. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  42512. }
  42513. }
  42514. };
  42515. Sound.prototype.setVolume = function (newVolume, time) {
  42516. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42517. if (time) {
  42518. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  42519. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  42520. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  42521. }
  42522. else {
  42523. this._soundGain.gain.value = newVolume;
  42524. }
  42525. }
  42526. this._volume = newVolume;
  42527. };
  42528. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  42529. this._playbackRate = newPlaybackRate;
  42530. if (this.isPlaying) {
  42531. if (this._streaming) {
  42532. this._htmlAudioElement.playbackRate = this._playbackRate;
  42533. }
  42534. else {
  42535. this._soundSource.playbackRate.value = this._playbackRate;
  42536. }
  42537. }
  42538. };
  42539. Sound.prototype.getVolume = function () {
  42540. return this._volume;
  42541. };
  42542. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  42543. var _this = this;
  42544. if (this._connectedMesh) {
  42545. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42546. this._registerFunc = null;
  42547. }
  42548. this._connectedMesh = meshToConnectTo;
  42549. if (!this.spatialSound) {
  42550. this.spatialSound = true;
  42551. this._createSpatialParameters();
  42552. if (this.isPlaying && this.loop) {
  42553. this.stop();
  42554. this.play();
  42555. }
  42556. }
  42557. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  42558. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  42559. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  42560. };
  42561. Sound.prototype.detachFromMesh = function () {
  42562. if (this._connectedMesh) {
  42563. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42564. this._registerFunc = null;
  42565. this._connectedMesh = null;
  42566. }
  42567. };
  42568. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  42569. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  42570. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  42571. this._updateDirection();
  42572. }
  42573. };
  42574. Sound.prototype.clone = function () {
  42575. var _this = this;
  42576. if (!this._streaming) {
  42577. var setBufferAndRun = function () {
  42578. if (_this._isReadyToPlay) {
  42579. clonedSound._audioBuffer = _this.getAudioBuffer();
  42580. clonedSound._isReadyToPlay = true;
  42581. if (clonedSound.autoplay) {
  42582. clonedSound.play();
  42583. }
  42584. }
  42585. else {
  42586. window.setTimeout(setBufferAndRun, 300);
  42587. }
  42588. };
  42589. var currentOptions = {
  42590. autoplay: this.autoplay, loop: this.loop,
  42591. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  42592. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  42593. refDistance: this.refDistance, distanceModel: this.distanceModel
  42594. };
  42595. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  42596. if (this.useCustomAttenuation) {
  42597. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  42598. }
  42599. clonedSound.setPosition(this._position);
  42600. clonedSound.setPlaybackRate(this._playbackRate);
  42601. setBufferAndRun();
  42602. return clonedSound;
  42603. }
  42604. else {
  42605. return null;
  42606. }
  42607. };
  42608. Sound.prototype.getAudioBuffer = function () {
  42609. return this._audioBuffer;
  42610. };
  42611. Sound.prototype.serialize = function () {
  42612. var serializationObject = {
  42613. name: this.name,
  42614. url: this.name,
  42615. autoplay: this.autoplay,
  42616. loop: this.loop,
  42617. volume: this._volume,
  42618. spatialSound: this.spatialSound,
  42619. maxDistance: this.maxDistance,
  42620. rolloffFactor: this.rolloffFactor,
  42621. refDistance: this.refDistance,
  42622. distanceModel: this.distanceModel,
  42623. playbackRate: this._playbackRate,
  42624. panningModel: this._panningModel,
  42625. soundTrackId: this.soundTrackId
  42626. };
  42627. if (this.spatialSound) {
  42628. if (this._connectedMesh)
  42629. serializationObject.connectedMeshId = this._connectedMesh.id;
  42630. serializationObject.position = this._position.asArray();
  42631. serializationObject.refDistance = this.refDistance;
  42632. serializationObject.distanceModel = this.distanceModel;
  42633. serializationObject.isDirectional = this._isDirectional;
  42634. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  42635. serializationObject.coneInnerAngle = this._coneInnerAngle;
  42636. serializationObject.coneOuterAngle = this._coneOuterAngle;
  42637. serializationObject.coneOuterGain = this._coneOuterGain;
  42638. }
  42639. return serializationObject;
  42640. };
  42641. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  42642. var soundName = parsedSound.name;
  42643. var soundUrl;
  42644. if (parsedSound.url) {
  42645. soundUrl = rootUrl + parsedSound.url;
  42646. }
  42647. else {
  42648. soundUrl = rootUrl + soundName;
  42649. }
  42650. var options = {
  42651. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  42652. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  42653. rolloffFactor: parsedSound.rolloffFactor,
  42654. refDistance: parsedSound.refDistance,
  42655. distanceModel: parsedSound.distanceModel,
  42656. playbackRate: parsedSound.playbackRate
  42657. };
  42658. var newSound;
  42659. if (!sourceSound) {
  42660. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  42661. scene._addPendingData(newSound);
  42662. }
  42663. else {
  42664. var setBufferAndRun = function () {
  42665. if (sourceSound._isReadyToPlay) {
  42666. newSound._audioBuffer = sourceSound.getAudioBuffer();
  42667. newSound._isReadyToPlay = true;
  42668. if (newSound.autoplay) {
  42669. newSound.play();
  42670. }
  42671. }
  42672. else {
  42673. window.setTimeout(setBufferAndRun, 300);
  42674. }
  42675. };
  42676. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  42677. setBufferAndRun();
  42678. }
  42679. if (parsedSound.position) {
  42680. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  42681. newSound.setPosition(soundPosition);
  42682. }
  42683. if (parsedSound.isDirectional) {
  42684. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  42685. if (parsedSound.localDirectionToMesh) {
  42686. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  42687. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  42688. }
  42689. }
  42690. if (parsedSound.connectedMeshId) {
  42691. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  42692. if (connectedMesh) {
  42693. newSound.attachToMesh(connectedMesh);
  42694. }
  42695. }
  42696. return newSound;
  42697. };
  42698. return Sound;
  42699. }());
  42700. BABYLON.Sound = Sound;
  42701. })(BABYLON || (BABYLON = {}));
  42702. //# sourceMappingURL=babylon.sound.js.map
  42703. var BABYLON;
  42704. (function (BABYLON) {
  42705. var SoundTrack = (function () {
  42706. function SoundTrack(scene, options) {
  42707. this.id = -1;
  42708. this._isMainTrack = false;
  42709. this._isInitialized = false;
  42710. this._scene = scene;
  42711. this.soundCollection = new Array();
  42712. this._options = options;
  42713. if (!this._isMainTrack) {
  42714. this._scene.soundTracks.push(this);
  42715. this.id = this._scene.soundTracks.length - 1;
  42716. }
  42717. }
  42718. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  42719. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42720. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  42721. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  42722. if (this._options) {
  42723. if (this._options.volume) {
  42724. this._outputAudioNode.gain.value = this._options.volume;
  42725. }
  42726. if (this._options.mainTrack) {
  42727. this._isMainTrack = this._options.mainTrack;
  42728. }
  42729. }
  42730. this._isInitialized = true;
  42731. }
  42732. };
  42733. SoundTrack.prototype.dispose = function () {
  42734. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42735. if (this._connectedAnalyser) {
  42736. this._connectedAnalyser.stopDebugCanvas();
  42737. }
  42738. while (this.soundCollection.length) {
  42739. this.soundCollection[0].dispose();
  42740. }
  42741. if (this._outputAudioNode) {
  42742. this._outputAudioNode.disconnect();
  42743. }
  42744. this._outputAudioNode = null;
  42745. }
  42746. };
  42747. SoundTrack.prototype.AddSound = function (sound) {
  42748. if (!this._isInitialized) {
  42749. this._initializeSoundTrackAudioGraph();
  42750. }
  42751. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42752. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  42753. }
  42754. if (sound.soundTrackId) {
  42755. if (sound.soundTrackId === -1) {
  42756. this._scene.mainSoundTrack.RemoveSound(sound);
  42757. }
  42758. else {
  42759. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  42760. }
  42761. }
  42762. this.soundCollection.push(sound);
  42763. sound.soundTrackId = this.id;
  42764. };
  42765. SoundTrack.prototype.RemoveSound = function (sound) {
  42766. var index = this.soundCollection.indexOf(sound);
  42767. if (index !== -1) {
  42768. this.soundCollection.splice(index, 1);
  42769. }
  42770. };
  42771. SoundTrack.prototype.setVolume = function (newVolume) {
  42772. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42773. this._outputAudioNode.gain.value = newVolume;
  42774. }
  42775. };
  42776. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  42777. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42778. for (var i = 0; i < this.soundCollection.length; i++) {
  42779. this.soundCollection[i].switchPanningModelToHRTF();
  42780. }
  42781. }
  42782. };
  42783. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  42784. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42785. for (var i = 0; i < this.soundCollection.length; i++) {
  42786. this.soundCollection[i].switchPanningModelToEqualPower();
  42787. }
  42788. }
  42789. };
  42790. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  42791. if (this._connectedAnalyser) {
  42792. this._connectedAnalyser.stopDebugCanvas();
  42793. }
  42794. this._connectedAnalyser = analyser;
  42795. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42796. this._outputAudioNode.disconnect();
  42797. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  42798. }
  42799. };
  42800. return SoundTrack;
  42801. }());
  42802. BABYLON.SoundTrack = SoundTrack;
  42803. })(BABYLON || (BABYLON = {}));
  42804. //# sourceMappingURL=babylon.soundtrack.js.map
  42805. var BABYLON;
  42806. (function (BABYLON) {
  42807. var Analyser = (function () {
  42808. function Analyser(scene) {
  42809. this.SMOOTHING = 0.75;
  42810. this.FFT_SIZE = 512;
  42811. this.BARGRAPHAMPLITUDE = 256;
  42812. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  42813. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  42814. this._scene = scene;
  42815. this._audioEngine = BABYLON.Engine.audioEngine;
  42816. if (this._audioEngine.canUseWebAudio) {
  42817. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  42818. this._webAudioAnalyser.minDecibels = -140;
  42819. this._webAudioAnalyser.maxDecibels = 0;
  42820. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  42821. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  42822. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  42823. }
  42824. }
  42825. Analyser.prototype.getFrequencyBinCount = function () {
  42826. if (this._audioEngine.canUseWebAudio) {
  42827. return this._webAudioAnalyser.frequencyBinCount;
  42828. }
  42829. else {
  42830. return 0;
  42831. }
  42832. };
  42833. Analyser.prototype.getByteFrequencyData = function () {
  42834. if (this._audioEngine.canUseWebAudio) {
  42835. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42836. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42837. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  42838. }
  42839. return this._byteFreqs;
  42840. };
  42841. Analyser.prototype.getByteTimeDomainData = function () {
  42842. if (this._audioEngine.canUseWebAudio) {
  42843. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42844. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42845. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  42846. }
  42847. return this._byteTime;
  42848. };
  42849. Analyser.prototype.getFloatFrequencyData = function () {
  42850. if (this._audioEngine.canUseWebAudio) {
  42851. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42852. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42853. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  42854. }
  42855. return this._floatFreqs;
  42856. };
  42857. Analyser.prototype.drawDebugCanvas = function () {
  42858. var _this = this;
  42859. if (this._audioEngine.canUseWebAudio) {
  42860. if (!this._debugCanvas) {
  42861. this._debugCanvas = document.createElement("canvas");
  42862. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  42863. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  42864. this._debugCanvas.style.position = "absolute";
  42865. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  42866. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  42867. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  42868. document.body.appendChild(this._debugCanvas);
  42869. this._registerFunc = function () {
  42870. _this.drawDebugCanvas();
  42871. };
  42872. this._scene.registerBeforeRender(this._registerFunc);
  42873. }
  42874. if (this._registerFunc) {
  42875. var workingArray = this.getByteFrequencyData();
  42876. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  42877. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  42878. // Draw the frequency domain chart.
  42879. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  42880. var value = workingArray[i];
  42881. var percent = value / this.BARGRAPHAMPLITUDE;
  42882. var height = this.DEBUGCANVASSIZE.height * percent;
  42883. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  42884. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  42885. var hue = i / this.getFrequencyBinCount() * 360;
  42886. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  42887. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  42888. }
  42889. }
  42890. }
  42891. };
  42892. Analyser.prototype.stopDebugCanvas = function () {
  42893. if (this._debugCanvas) {
  42894. this._scene.unregisterBeforeRender(this._registerFunc);
  42895. this._registerFunc = null;
  42896. document.body.removeChild(this._debugCanvas);
  42897. this._debugCanvas = null;
  42898. this._debugCanvasContext = null;
  42899. }
  42900. };
  42901. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  42902. if (this._audioEngine.canUseWebAudio) {
  42903. inputAudioNode.connect(this._webAudioAnalyser);
  42904. this._webAudioAnalyser.connect(outputAudioNode);
  42905. }
  42906. };
  42907. Analyser.prototype.dispose = function () {
  42908. if (this._audioEngine.canUseWebAudio) {
  42909. this._webAudioAnalyser.disconnect();
  42910. }
  42911. };
  42912. return Analyser;
  42913. }());
  42914. BABYLON.Analyser = Analyser;
  42915. })(BABYLON || (BABYLON = {}));
  42916. //# sourceMappingURL=babylon.analyser.js.map
  42917. var BABYLON;
  42918. (function (BABYLON) {
  42919. var CubeTexture = (function (_super) {
  42920. __extends(CubeTexture, _super);
  42921. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  42922. if (onLoad === void 0) { onLoad = null; }
  42923. if (onError === void 0) { onError = null; }
  42924. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  42925. var _this = _super.call(this, scene) || this;
  42926. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  42927. _this.name = rootUrl;
  42928. _this.url = rootUrl;
  42929. _this._noMipmap = noMipmap;
  42930. _this.hasAlpha = false;
  42931. _this._format = format;
  42932. if (!rootUrl && !files) {
  42933. return _this;
  42934. }
  42935. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  42936. if (!files) {
  42937. if (!extensions) {
  42938. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  42939. }
  42940. files = [];
  42941. for (var index = 0; index < extensions.length; index++) {
  42942. files.push(rootUrl + extensions[index]);
  42943. }
  42944. _this._extensions = extensions;
  42945. }
  42946. _this._files = files;
  42947. if (!_this._texture) {
  42948. if (!scene.useDelayedTextureLoading) {
  42949. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  42950. }
  42951. else {
  42952. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  42953. }
  42954. }
  42955. else if (onLoad) {
  42956. if (_this._texture.isReady) {
  42957. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  42958. }
  42959. else {
  42960. _this._texture.onLoadedCallbacks.push(onLoad);
  42961. }
  42962. }
  42963. _this.isCube = true;
  42964. _this._textureMatrix = BABYLON.Matrix.Identity();
  42965. return _this;
  42966. }
  42967. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  42968. return new CubeTexture("", scene, null, noMipmap, files);
  42969. };
  42970. // Methods
  42971. CubeTexture.prototype.delayLoad = function () {
  42972. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  42973. return;
  42974. }
  42975. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  42976. this._texture = this._getFromCache(this.url, this._noMipmap);
  42977. if (!this._texture) {
  42978. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  42979. }
  42980. };
  42981. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  42982. return this._textureMatrix;
  42983. };
  42984. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  42985. var texture = BABYLON.SerializationHelper.Parse(function () {
  42986. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  42987. }, parsedTexture, scene);
  42988. // Animations
  42989. if (parsedTexture.animations) {
  42990. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  42991. var parsedAnimation = parsedTexture.animations[animationIndex];
  42992. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  42993. }
  42994. }
  42995. return texture;
  42996. };
  42997. CubeTexture.prototype.clone = function () {
  42998. var _this = this;
  42999. return BABYLON.SerializationHelper.Clone(function () {
  43000. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  43001. }, this);
  43002. };
  43003. return CubeTexture;
  43004. }(BABYLON.BaseTexture));
  43005. BABYLON.CubeTexture = CubeTexture;
  43006. })(BABYLON || (BABYLON = {}));
  43007. //# sourceMappingURL=babylon.cubeTexture.js.map
  43008. var BABYLON;
  43009. (function (BABYLON) {
  43010. var RenderTargetTexture = (function (_super) {
  43011. __extends(RenderTargetTexture, _super);
  43012. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  43013. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  43014. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43015. if (isCube === void 0) { isCube = false; }
  43016. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43017. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  43018. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  43019. if (isMulti === void 0) { isMulti = false; }
  43020. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  43021. _this.isCube = isCube;
  43022. /**
  43023. * Use this list to define the list of mesh you want to render.
  43024. */
  43025. _this.renderList = new Array();
  43026. _this.renderParticles = true;
  43027. _this.renderSprites = false;
  43028. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  43029. // Events
  43030. /**
  43031. * An event triggered when the texture is unbind.
  43032. * @type {BABYLON.Observable}
  43033. */
  43034. _this.onAfterUnbindObservable = new BABYLON.Observable();
  43035. /**
  43036. * An event triggered before rendering the texture
  43037. * @type {BABYLON.Observable}
  43038. */
  43039. _this.onBeforeRenderObservable = new BABYLON.Observable();
  43040. /**
  43041. * An event triggered after rendering the texture
  43042. * @type {BABYLON.Observable}
  43043. */
  43044. _this.onAfterRenderObservable = new BABYLON.Observable();
  43045. /**
  43046. * An event triggered after the texture clear
  43047. * @type {BABYLON.Observable}
  43048. */
  43049. _this.onClearObservable = new BABYLON.Observable();
  43050. _this._currentRefreshId = -1;
  43051. _this._refreshRate = 1;
  43052. _this._samples = 1;
  43053. scene = _this.getScene();
  43054. _this.name = name;
  43055. _this.isRenderTarget = true;
  43056. _this._size = size;
  43057. _this._generateMipMaps = generateMipMaps;
  43058. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  43059. // Rendering groups
  43060. _this._renderingManager = new BABYLON.RenderingManager(scene);
  43061. if (isMulti) {
  43062. return _this;
  43063. }
  43064. _this._renderTargetOptions = {
  43065. generateMipMaps: generateMipMaps,
  43066. type: type,
  43067. samplingMode: samplingMode,
  43068. generateDepthBuffer: generateDepthBuffer,
  43069. generateStencilBuffer: generateStencilBuffer
  43070. };
  43071. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  43072. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43073. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43074. }
  43075. if (isCube) {
  43076. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  43077. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  43078. _this._textureMatrix = BABYLON.Matrix.Identity();
  43079. }
  43080. else {
  43081. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  43082. }
  43083. return _this;
  43084. }
  43085. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  43086. get: function () {
  43087. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  43088. },
  43089. enumerable: true,
  43090. configurable: true
  43091. });
  43092. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  43093. get: function () {
  43094. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  43095. },
  43096. enumerable: true,
  43097. configurable: true
  43098. });
  43099. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  43100. get: function () {
  43101. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  43102. },
  43103. enumerable: true,
  43104. configurable: true
  43105. });
  43106. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  43107. set: function (callback) {
  43108. if (this._onAfterUnbindObserver) {
  43109. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  43110. }
  43111. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  43112. },
  43113. enumerable: true,
  43114. configurable: true
  43115. });
  43116. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  43117. set: function (callback) {
  43118. if (this._onBeforeRenderObserver) {
  43119. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  43120. }
  43121. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  43122. },
  43123. enumerable: true,
  43124. configurable: true
  43125. });
  43126. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  43127. set: function (callback) {
  43128. if (this._onAfterRenderObserver) {
  43129. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  43130. }
  43131. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  43132. },
  43133. enumerable: true,
  43134. configurable: true
  43135. });
  43136. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  43137. set: function (callback) {
  43138. if (this._onClearObserver) {
  43139. this.onClearObservable.remove(this._onClearObserver);
  43140. }
  43141. this._onClearObserver = this.onClearObservable.add(callback);
  43142. },
  43143. enumerable: true,
  43144. configurable: true
  43145. });
  43146. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  43147. get: function () {
  43148. return this._renderTargetOptions;
  43149. },
  43150. enumerable: true,
  43151. configurable: true
  43152. });
  43153. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  43154. get: function () {
  43155. return this._samples;
  43156. },
  43157. set: function (value) {
  43158. if (this._samples === value) {
  43159. return;
  43160. }
  43161. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  43162. },
  43163. enumerable: true,
  43164. configurable: true
  43165. });
  43166. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  43167. this._currentRefreshId = -1;
  43168. };
  43169. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  43170. get: function () {
  43171. return this._refreshRate;
  43172. },
  43173. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  43174. set: function (value) {
  43175. this._refreshRate = value;
  43176. this.resetRefreshCounter();
  43177. },
  43178. enumerable: true,
  43179. configurable: true
  43180. });
  43181. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  43182. if (!this._postProcessManager) {
  43183. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  43184. this._postProcesses = new Array();
  43185. }
  43186. this._postProcesses.push(postProcess);
  43187. this._postProcesses[0].autoClear = false;
  43188. };
  43189. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  43190. if (!this._postProcesses) {
  43191. return;
  43192. }
  43193. if (dispose) {
  43194. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  43195. var postProcess = _a[_i];
  43196. postProcess.dispose();
  43197. postProcess = null;
  43198. }
  43199. }
  43200. this._postProcesses = [];
  43201. };
  43202. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  43203. if (!this._postProcesses) {
  43204. return;
  43205. }
  43206. var index = this._postProcesses.indexOf(postProcess);
  43207. if (index === -1) {
  43208. return;
  43209. }
  43210. this._postProcesses.splice(index, 1);
  43211. if (this._postProcesses.length > 0) {
  43212. this._postProcesses[0].autoClear = false;
  43213. }
  43214. };
  43215. RenderTargetTexture.prototype._shouldRender = function () {
  43216. if (this._currentRefreshId === -1) {
  43217. this._currentRefreshId = 1;
  43218. return true;
  43219. }
  43220. if (this.refreshRate === this._currentRefreshId) {
  43221. this._currentRefreshId = 1;
  43222. return true;
  43223. }
  43224. this._currentRefreshId++;
  43225. return false;
  43226. };
  43227. RenderTargetTexture.prototype.isReady = function () {
  43228. if (!this.getScene().renderTargetsEnabled) {
  43229. return false;
  43230. }
  43231. return _super.prototype.isReady.call(this);
  43232. };
  43233. RenderTargetTexture.prototype.getRenderSize = function () {
  43234. return this._size;
  43235. };
  43236. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  43237. get: function () {
  43238. return true;
  43239. },
  43240. enumerable: true,
  43241. configurable: true
  43242. });
  43243. RenderTargetTexture.prototype.scale = function (ratio) {
  43244. var newSize = this._size * ratio;
  43245. this.resize(newSize);
  43246. };
  43247. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  43248. if (this.isCube) {
  43249. return this._textureMatrix;
  43250. }
  43251. return _super.prototype.getReflectionTextureMatrix.call(this);
  43252. };
  43253. RenderTargetTexture.prototype.resize = function (size) {
  43254. this.releaseInternalTexture();
  43255. if (this.isCube) {
  43256. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  43257. }
  43258. else {
  43259. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  43260. }
  43261. };
  43262. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  43263. var scene = this.getScene();
  43264. var engine = scene.getEngine();
  43265. if (this.useCameraPostProcesses !== undefined) {
  43266. useCameraPostProcess = this.useCameraPostProcesses;
  43267. }
  43268. if (this._waitingRenderList) {
  43269. this.renderList = [];
  43270. for (var index = 0; index < this._waitingRenderList.length; index++) {
  43271. var id = this._waitingRenderList[index];
  43272. this.renderList.push(scene.getMeshByID(id));
  43273. }
  43274. delete this._waitingRenderList;
  43275. }
  43276. // Is predicate defined?
  43277. if (this.renderListPredicate) {
  43278. this.renderList.splice(0); // Clear previous renderList
  43279. var sceneMeshes = this.getScene().meshes;
  43280. for (var index = 0; index < sceneMeshes.length; index++) {
  43281. var mesh = sceneMeshes[index];
  43282. if (this.renderListPredicate(mesh)) {
  43283. this.renderList.push(mesh);
  43284. }
  43285. }
  43286. }
  43287. if (this.renderList && this.renderList.length === 0) {
  43288. return;
  43289. }
  43290. // Set custom projection.
  43291. // Needs to be before binding to prevent changing the aspect ratio.
  43292. var camera;
  43293. if (this.activeCamera) {
  43294. camera = this.activeCamera;
  43295. engine.setViewport(this.activeCamera.viewport);
  43296. if (this.activeCamera !== scene.activeCamera) {
  43297. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  43298. }
  43299. }
  43300. else {
  43301. camera = scene.activeCamera;
  43302. engine.setViewport(scene.activeCamera.viewport);
  43303. }
  43304. // Prepare renderingManager
  43305. this._renderingManager.reset();
  43306. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  43307. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  43308. var sceneRenderId = scene.getRenderId();
  43309. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  43310. var mesh = currentRenderList[meshIndex];
  43311. if (mesh) {
  43312. if (!mesh.isReady()) {
  43313. // Reset _currentRefreshId
  43314. this.resetRefreshCounter();
  43315. continue;
  43316. }
  43317. mesh._preActivateForIntermediateRendering(sceneRenderId);
  43318. var isMasked = void 0;
  43319. if (!this.renderList) {
  43320. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  43321. }
  43322. else {
  43323. isMasked = false;
  43324. }
  43325. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  43326. mesh._activate(sceneRenderId);
  43327. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  43328. var subMesh = mesh.subMeshes[subIndex];
  43329. scene._activeIndices.addCount(subMesh.indexCount, false);
  43330. this._renderingManager.dispatch(subMesh);
  43331. }
  43332. }
  43333. }
  43334. }
  43335. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  43336. var particleSystem = scene.particleSystems[particleIndex];
  43337. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  43338. continue;
  43339. }
  43340. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  43341. this._renderingManager.dispatchParticles(particleSystem);
  43342. }
  43343. }
  43344. if (this.isCube) {
  43345. for (var face = 0; face < 6; face++) {
  43346. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  43347. scene.incrementRenderId();
  43348. scene.resetCachedMaterial();
  43349. }
  43350. }
  43351. else {
  43352. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  43353. }
  43354. this.onAfterUnbindObservable.notifyObservers(this);
  43355. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  43356. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  43357. }
  43358. engine.setViewport(scene.activeCamera.viewport);
  43359. scene.resetCachedMaterial();
  43360. };
  43361. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  43362. var _this = this;
  43363. var scene = this.getScene();
  43364. var engine = scene.getEngine();
  43365. // Bind
  43366. if (this._postProcessManager) {
  43367. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  43368. }
  43369. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  43370. if (this.isCube) {
  43371. engine.bindFramebuffer(this._texture, faceIndex);
  43372. }
  43373. else {
  43374. engine.bindFramebuffer(this._texture);
  43375. }
  43376. }
  43377. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  43378. // Clear
  43379. if (this.onClearObservable.hasObservers()) {
  43380. this.onClearObservable.notifyObservers(engine);
  43381. }
  43382. else {
  43383. engine.clear(scene.clearColor, true, true, true);
  43384. }
  43385. if (!this._doNotChangeAspectRatio) {
  43386. scene.updateTransformMatrix(true);
  43387. }
  43388. // Render
  43389. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  43390. if (this._postProcessManager) {
  43391. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  43392. }
  43393. else if (useCameraPostProcess) {
  43394. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  43395. }
  43396. if (!this._doNotChangeAspectRatio) {
  43397. scene.updateTransformMatrix(true);
  43398. }
  43399. // Dump ?
  43400. if (dumpForDebug) {
  43401. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  43402. }
  43403. // Unbind
  43404. if (!this.isCube || faceIndex === 5) {
  43405. if (this.isCube) {
  43406. if (faceIndex === 5) {
  43407. engine.generateMipMapsForCubemap(this._texture);
  43408. }
  43409. }
  43410. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  43411. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  43412. });
  43413. }
  43414. else {
  43415. this.onAfterRenderObservable.notifyObservers(faceIndex);
  43416. }
  43417. };
  43418. /**
  43419. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  43420. * This allowed control for front to back rendering or reversly depending of the special needs.
  43421. *
  43422. * @param renderingGroupId The rendering group id corresponding to its index
  43423. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  43424. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  43425. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  43426. */
  43427. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  43428. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  43429. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  43430. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  43431. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  43432. };
  43433. /**
  43434. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  43435. *
  43436. * @param renderingGroupId The rendering group id corresponding to its index
  43437. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  43438. */
  43439. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  43440. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  43441. };
  43442. RenderTargetTexture.prototype.clone = function () {
  43443. var textureSize = this.getSize();
  43444. 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);
  43445. // Base texture
  43446. newTexture.hasAlpha = this.hasAlpha;
  43447. newTexture.level = this.level;
  43448. // RenderTarget Texture
  43449. newTexture.coordinatesMode = this.coordinatesMode;
  43450. newTexture.renderList = this.renderList.slice(0);
  43451. return newTexture;
  43452. };
  43453. RenderTargetTexture.prototype.serialize = function () {
  43454. if (!this.name) {
  43455. return null;
  43456. }
  43457. var serializationObject = _super.prototype.serialize.call(this);
  43458. serializationObject.renderTargetSize = this.getRenderSize();
  43459. serializationObject.renderList = [];
  43460. for (var index = 0; index < this.renderList.length; index++) {
  43461. serializationObject.renderList.push(this.renderList[index].id);
  43462. }
  43463. return serializationObject;
  43464. };
  43465. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  43466. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  43467. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  43468. };
  43469. RenderTargetTexture.prototype.dispose = function () {
  43470. if (this._postProcessManager) {
  43471. this._postProcessManager.dispose();
  43472. this._postProcessManager = null;
  43473. }
  43474. this.clearPostProcesses(true);
  43475. // Remove from custom render targets
  43476. var scene = this.getScene();
  43477. var index = scene.customRenderTargets.indexOf(this);
  43478. if (index >= 0) {
  43479. scene.customRenderTargets.splice(index, 1);
  43480. }
  43481. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  43482. var camera = _a[_i];
  43483. index = camera.customRenderTargets.indexOf(this);
  43484. if (index >= 0) {
  43485. camera.customRenderTargets.splice(index, 1);
  43486. }
  43487. }
  43488. _super.prototype.dispose.call(this);
  43489. };
  43490. return RenderTargetTexture;
  43491. }(BABYLON.Texture));
  43492. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  43493. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  43494. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  43495. BABYLON.RenderTargetTexture = RenderTargetTexture;
  43496. })(BABYLON || (BABYLON = {}));
  43497. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  43498. var BABYLON;
  43499. (function (BABYLON) {
  43500. ;
  43501. var MultiRenderTarget = (function (_super) {
  43502. __extends(MultiRenderTarget, _super);
  43503. function MultiRenderTarget(name, size, count, scene, options) {
  43504. var _this = this;
  43505. options = options || {};
  43506. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  43507. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  43508. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  43509. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  43510. if (!_this.isSupported) {
  43511. _this.dispose();
  43512. return;
  43513. }
  43514. var types = [];
  43515. var samplingModes = [];
  43516. for (var i = 0; i < count; i++) {
  43517. if (options.types && options.types[i]) {
  43518. types.push(options.types[i]);
  43519. }
  43520. else {
  43521. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  43522. }
  43523. if (options.samplingModes && options.samplingModes[i]) {
  43524. samplingModes.push(options.samplingModes[i]);
  43525. }
  43526. else {
  43527. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  43528. }
  43529. }
  43530. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  43531. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  43532. _this._count = count;
  43533. _this._size = size;
  43534. _this._multiRenderTargetOptions = {
  43535. samplingModes: samplingModes,
  43536. generateMipMaps: generateMipMaps,
  43537. generateDepthBuffer: generateDepthBuffer,
  43538. generateStencilBuffer: generateStencilBuffer,
  43539. generateDepthTexture: generateDepthTexture,
  43540. types: types,
  43541. textureCount: count
  43542. };
  43543. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  43544. _this._createInternalTextures();
  43545. return _this;
  43546. }
  43547. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  43548. get: function () {
  43549. var engine = this.getScene().getEngine();
  43550. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  43551. },
  43552. enumerable: true,
  43553. configurable: true
  43554. });
  43555. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  43556. get: function () {
  43557. return this._textures;
  43558. },
  43559. enumerable: true,
  43560. configurable: true
  43561. });
  43562. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  43563. get: function () {
  43564. return this._textures[this._textures.length - 1];
  43565. },
  43566. enumerable: true,
  43567. configurable: true
  43568. });
  43569. MultiRenderTarget.prototype._createInternalTextures = function () {
  43570. this._textures = [];
  43571. for (var i = 0; i < this._webGLTextures.length; i++) {
  43572. var texture = new BABYLON.Texture(null, this.getScene());
  43573. texture._texture = this._webGLTextures[i];
  43574. this._textures.push(texture);
  43575. }
  43576. // Keeps references to frame buffer and stencil/depth buffer
  43577. this._texture = this._webGLTextures[0];
  43578. };
  43579. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  43580. get: function () {
  43581. return this._samples;
  43582. },
  43583. set: function (value) {
  43584. if (this._samples === value) {
  43585. return;
  43586. }
  43587. for (var i = 0; i < this._webGLTextures.length; i++) {
  43588. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  43589. }
  43590. },
  43591. enumerable: true,
  43592. configurable: true
  43593. });
  43594. MultiRenderTarget.prototype.resize = function (size) {
  43595. this.releaseInternalTextures();
  43596. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  43597. this._createInternalTextures();
  43598. };
  43599. MultiRenderTarget.prototype.dispose = function () {
  43600. this.releaseInternalTextures();
  43601. _super.prototype.dispose.call(this);
  43602. };
  43603. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  43604. if (!this._webGLTextures) {
  43605. return;
  43606. }
  43607. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  43608. if (this._webGLTextures[i] !== undefined) {
  43609. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  43610. this._webGLTextures.splice(i, 1);
  43611. }
  43612. }
  43613. };
  43614. return MultiRenderTarget;
  43615. }(BABYLON.RenderTargetTexture));
  43616. BABYLON.MultiRenderTarget = MultiRenderTarget;
  43617. })(BABYLON || (BABYLON = {}));
  43618. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  43619. /// <reference path="babylon.renderTargetTexture.ts" />
  43620. var BABYLON;
  43621. (function (BABYLON) {
  43622. var MirrorTexture = (function (_super) {
  43623. __extends(MirrorTexture, _super);
  43624. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  43625. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43626. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  43627. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  43628. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  43629. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  43630. _this._transformMatrix = BABYLON.Matrix.Zero();
  43631. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  43632. _this._blurKernelX = 0;
  43633. _this._blurKernelY = 0;
  43634. _this._blurRatio = 1.0;
  43635. _this.onBeforeRenderObservable.add(function () {
  43636. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  43637. _this._savedViewMatrix = scene.getViewMatrix();
  43638. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  43639. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  43640. scene.clipPlane = _this.mirrorPlane;
  43641. scene.getEngine().cullBackFaces = false;
  43642. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  43643. });
  43644. _this.onAfterRenderObservable.add(function () {
  43645. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  43646. scene.getEngine().cullBackFaces = true;
  43647. scene._mirroredCameraPosition = null;
  43648. delete scene.clipPlane;
  43649. });
  43650. return _this;
  43651. }
  43652. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  43653. get: function () {
  43654. return this._blurRatio;
  43655. },
  43656. set: function (value) {
  43657. if (this._blurRatio === value) {
  43658. return;
  43659. }
  43660. this._blurRatio = value;
  43661. this._preparePostProcesses();
  43662. },
  43663. enumerable: true,
  43664. configurable: true
  43665. });
  43666. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  43667. set: function (value) {
  43668. this.blurKernelX = value;
  43669. this.blurKernelY = value;
  43670. },
  43671. enumerable: true,
  43672. configurable: true
  43673. });
  43674. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  43675. get: function () {
  43676. return this._blurKernelX;
  43677. },
  43678. set: function (value) {
  43679. if (this._blurKernelX === value) {
  43680. return;
  43681. }
  43682. this._blurKernelX = value;
  43683. this._preparePostProcesses();
  43684. },
  43685. enumerable: true,
  43686. configurable: true
  43687. });
  43688. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  43689. get: function () {
  43690. return this._blurKernelY;
  43691. },
  43692. set: function (value) {
  43693. if (this._blurKernelY === value) {
  43694. return;
  43695. }
  43696. this._blurKernelY = value;
  43697. this._preparePostProcesses();
  43698. },
  43699. enumerable: true,
  43700. configurable: true
  43701. });
  43702. MirrorTexture.prototype._preparePostProcesses = function () {
  43703. this.clearPostProcesses(true);
  43704. if (this._blurKernelX && this._blurKernelY) {
  43705. var engine = this.getScene().getEngine();
  43706. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  43707. 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);
  43708. this._blurX.autoClear = false;
  43709. if (this._blurRatio === 1 && this.samples < 2) {
  43710. this._blurX.outputTexture = this._texture;
  43711. }
  43712. else {
  43713. this._blurX.alwaysForcePOT = true;
  43714. }
  43715. 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);
  43716. this._blurY.autoClear = false;
  43717. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  43718. this.addPostProcess(this._blurX);
  43719. this.addPostProcess(this._blurY);
  43720. }
  43721. };
  43722. MirrorTexture.prototype.clone = function () {
  43723. var textureSize = this.getSize();
  43724. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  43725. // Base texture
  43726. newTexture.hasAlpha = this.hasAlpha;
  43727. newTexture.level = this.level;
  43728. // Mirror Texture
  43729. newTexture.mirrorPlane = this.mirrorPlane.clone();
  43730. newTexture.renderList = this.renderList.slice(0);
  43731. return newTexture;
  43732. };
  43733. MirrorTexture.prototype.serialize = function () {
  43734. if (!this.name) {
  43735. return null;
  43736. }
  43737. var serializationObject = _super.prototype.serialize.call(this);
  43738. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  43739. return serializationObject;
  43740. };
  43741. return MirrorTexture;
  43742. }(BABYLON.RenderTargetTexture));
  43743. BABYLON.MirrorTexture = MirrorTexture;
  43744. })(BABYLON || (BABYLON = {}));
  43745. //# sourceMappingURL=babylon.mirrorTexture.js.map
  43746. /// <reference path="babylon.renderTargetTexture.ts" />
  43747. var BABYLON;
  43748. (function (BABYLON) {
  43749. /**
  43750. * Creates a refraction texture used by refraction channel of the standard material.
  43751. * @param name the texture name
  43752. * @param size size of the underlying texture
  43753. * @param scene root scene
  43754. */
  43755. var RefractionTexture = (function (_super) {
  43756. __extends(RefractionTexture, _super);
  43757. function RefractionTexture(name, size, scene, generateMipMaps) {
  43758. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  43759. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  43760. _this.depth = 2.0;
  43761. _this.onBeforeRenderObservable.add(function () {
  43762. scene.clipPlane = _this.refractionPlane;
  43763. });
  43764. _this.onAfterRenderObservable.add(function () {
  43765. delete scene.clipPlane;
  43766. });
  43767. return _this;
  43768. }
  43769. RefractionTexture.prototype.clone = function () {
  43770. var textureSize = this.getSize();
  43771. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  43772. // Base texture
  43773. newTexture.hasAlpha = this.hasAlpha;
  43774. newTexture.level = this.level;
  43775. // Refraction Texture
  43776. newTexture.refractionPlane = this.refractionPlane.clone();
  43777. newTexture.renderList = this.renderList.slice(0);
  43778. newTexture.depth = this.depth;
  43779. return newTexture;
  43780. };
  43781. RefractionTexture.prototype.serialize = function () {
  43782. if (!this.name) {
  43783. return null;
  43784. }
  43785. var serializationObject = _super.prototype.serialize.call(this);
  43786. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  43787. serializationObject.depth = this.depth;
  43788. return serializationObject;
  43789. };
  43790. return RefractionTexture;
  43791. }(BABYLON.RenderTargetTexture));
  43792. BABYLON.RefractionTexture = RefractionTexture;
  43793. })(BABYLON || (BABYLON = {}));
  43794. //# sourceMappingURL=babylon.refractionTexture.js.map
  43795. /// <reference path="babylon.texture.ts" />
  43796. var BABYLON;
  43797. (function (BABYLON) {
  43798. var DynamicTexture = (function (_super) {
  43799. __extends(DynamicTexture, _super);
  43800. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  43801. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43802. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  43803. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  43804. _this.name = name;
  43805. var engine = _this.getScene().getEngine();
  43806. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43807. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43808. _this._generateMipMaps = generateMipMaps;
  43809. if (options.getContext) {
  43810. _this._canvas = options;
  43811. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  43812. }
  43813. else {
  43814. _this._canvas = document.createElement("canvas");
  43815. if (options.width) {
  43816. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  43817. }
  43818. else {
  43819. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  43820. }
  43821. }
  43822. var textureSize = _this.getSize();
  43823. _this._canvas.width = textureSize.width;
  43824. _this._canvas.height = textureSize.height;
  43825. _this._context = _this._canvas.getContext("2d");
  43826. return _this;
  43827. }
  43828. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  43829. get: function () {
  43830. return true;
  43831. },
  43832. enumerable: true,
  43833. configurable: true
  43834. });
  43835. DynamicTexture.prototype._recreate = function (textureSize) {
  43836. this._canvas.width = textureSize.width;
  43837. this._canvas.height = textureSize.height;
  43838. this.releaseInternalTexture();
  43839. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  43840. };
  43841. DynamicTexture.prototype.scale = function (ratio) {
  43842. var textureSize = this.getSize();
  43843. textureSize.width *= ratio;
  43844. textureSize.height *= ratio;
  43845. this._recreate(textureSize);
  43846. };
  43847. DynamicTexture.prototype.scaleTo = function (width, height) {
  43848. var textureSize = this.getSize();
  43849. textureSize.width = width;
  43850. textureSize.height = height;
  43851. this._recreate(textureSize);
  43852. };
  43853. DynamicTexture.prototype.getContext = function () {
  43854. return this._context;
  43855. };
  43856. DynamicTexture.prototype.clear = function () {
  43857. var size = this.getSize();
  43858. this._context.fillRect(0, 0, size.width, size.height);
  43859. };
  43860. DynamicTexture.prototype.update = function (invertY) {
  43861. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  43862. };
  43863. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  43864. if (update === void 0) { update = true; }
  43865. var size = this.getSize();
  43866. if (clearColor) {
  43867. this._context.fillStyle = clearColor;
  43868. this._context.fillRect(0, 0, size.width, size.height);
  43869. }
  43870. this._context.font = font;
  43871. if (x === null || x === undefined) {
  43872. var textSize = this._context.measureText(text);
  43873. x = (size.width - textSize.width) / 2;
  43874. }
  43875. if (y === null || y === undefined) {
  43876. var fontSize = parseInt((font.replace(/\D/g, '')));
  43877. ;
  43878. y = (size.height / 2) + (fontSize / 3.65);
  43879. }
  43880. this._context.fillStyle = color;
  43881. this._context.fillText(text, x, y);
  43882. if (update) {
  43883. this.update(invertY);
  43884. }
  43885. };
  43886. DynamicTexture.prototype.clone = function () {
  43887. var textureSize = this.getSize();
  43888. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  43889. // Base texture
  43890. newTexture.hasAlpha = this.hasAlpha;
  43891. newTexture.level = this.level;
  43892. // Dynamic Texture
  43893. newTexture.wrapU = this.wrapU;
  43894. newTexture.wrapV = this.wrapV;
  43895. return newTexture;
  43896. };
  43897. return DynamicTexture;
  43898. }(BABYLON.Texture));
  43899. BABYLON.DynamicTexture = DynamicTexture;
  43900. })(BABYLON || (BABYLON = {}));
  43901. //# sourceMappingURL=babylon.dynamicTexture.js.map
  43902. var BABYLON;
  43903. (function (BABYLON) {
  43904. var VideoTexture = (function (_super) {
  43905. __extends(VideoTexture, _super);
  43906. /**
  43907. * Creates a video texture.
  43908. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  43909. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  43910. * @param {BABYLON.Scene} scene is obviously the current scene.
  43911. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  43912. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  43913. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  43914. */
  43915. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  43916. if (generateMipMaps === void 0) { generateMipMaps = false; }
  43917. if (invertY === void 0) { invertY = false; }
  43918. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43919. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  43920. _this._autoLaunch = true;
  43921. var urls;
  43922. _this.name = name;
  43923. if (urlsOrVideo instanceof HTMLVideoElement) {
  43924. _this.video = urlsOrVideo;
  43925. }
  43926. else {
  43927. urls = urlsOrVideo;
  43928. _this.video = document.createElement("video");
  43929. _this.video.autoplay = false;
  43930. _this.video.loop = true;
  43931. }
  43932. _this._generateMipMaps = generateMipMaps;
  43933. _this._samplingMode = samplingMode;
  43934. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  43935. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  43936. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  43937. }
  43938. else {
  43939. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43940. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43941. _this._generateMipMaps = false;
  43942. }
  43943. if (urls) {
  43944. _this.video.addEventListener("canplay", function () {
  43945. _this._createTexture();
  43946. });
  43947. urls.forEach(function (url) {
  43948. var source = document.createElement("source");
  43949. source.src = url;
  43950. _this.video.appendChild(source);
  43951. });
  43952. }
  43953. else {
  43954. _this._createTexture();
  43955. }
  43956. _this._lastUpdate = BABYLON.Tools.Now;
  43957. return _this;
  43958. }
  43959. VideoTexture.prototype.__setTextureReady = function () {
  43960. this._texture.isReady = true;
  43961. };
  43962. VideoTexture.prototype._createTexture = function () {
  43963. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  43964. if (this._autoLaunch) {
  43965. this._autoLaunch = false;
  43966. this.video.play();
  43967. }
  43968. this._setTextureReady = this.__setTextureReady.bind(this);
  43969. this.video.addEventListener("playing", this._setTextureReady);
  43970. };
  43971. VideoTexture.prototype.update = function () {
  43972. var now = BABYLON.Tools.Now;
  43973. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  43974. return false;
  43975. }
  43976. this._lastUpdate = now;
  43977. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  43978. return true;
  43979. };
  43980. VideoTexture.prototype.dispose = function () {
  43981. _super.prototype.dispose.call(this);
  43982. this.video.removeEventListener("playing", this._setTextureReady);
  43983. };
  43984. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  43985. var video = document.createElement("video");
  43986. var constraintsDeviceId;
  43987. if (constraints && constraints.deviceId) {
  43988. constraintsDeviceId = {
  43989. exact: constraints.deviceId
  43990. };
  43991. }
  43992. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  43993. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  43994. if (navigator.getUserMedia) {
  43995. navigator.getUserMedia({
  43996. video: {
  43997. deviceId: constraintsDeviceId,
  43998. width: {
  43999. min: (constraints && constraints.minWidth) || 256,
  44000. max: (constraints && constraints.maxWidth) || 640
  44001. },
  44002. height: {
  44003. min: (constraints && constraints.minHeight) || 256,
  44004. max: (constraints && constraints.maxHeight) || 480
  44005. }
  44006. }
  44007. }, function (stream) {
  44008. if (video.mozSrcObject !== undefined) {
  44009. video.mozSrcObject = stream;
  44010. }
  44011. else {
  44012. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  44013. }
  44014. video.play();
  44015. if (onReady) {
  44016. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  44017. }
  44018. }, function (e) {
  44019. BABYLON.Tools.Error(e.name);
  44020. });
  44021. }
  44022. };
  44023. return VideoTexture;
  44024. }(BABYLON.Texture));
  44025. BABYLON.VideoTexture = VideoTexture;
  44026. })(BABYLON || (BABYLON = {}));
  44027. //# sourceMappingURL=babylon.videoTexture.js.map
  44028. var BABYLON;
  44029. (function (BABYLON) {
  44030. var RawTexture = (function (_super) {
  44031. __extends(RawTexture, _super);
  44032. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  44033. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44034. if (invertY === void 0) { invertY = false; }
  44035. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44036. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  44037. _this.format = format;
  44038. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  44039. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44040. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44041. return _this;
  44042. }
  44043. RawTexture.prototype.update = function (data) {
  44044. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  44045. };
  44046. // Statics
  44047. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44048. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44049. if (invertY === void 0) { invertY = false; }
  44050. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44051. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  44052. };
  44053. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44054. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44055. if (invertY === void 0) { invertY = false; }
  44056. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44057. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44058. };
  44059. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44060. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44061. if (invertY === void 0) { invertY = false; }
  44062. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44063. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44064. };
  44065. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44066. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44067. if (invertY === void 0) { invertY = false; }
  44068. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44069. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  44070. };
  44071. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44072. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44073. if (invertY === void 0) { invertY = false; }
  44074. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44075. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  44076. };
  44077. return RawTexture;
  44078. }(BABYLON.Texture));
  44079. BABYLON.RawTexture = RawTexture;
  44080. })(BABYLON || (BABYLON = {}));
  44081. //# sourceMappingURL=babylon.rawTexture.js.map
  44082. var BABYLON;
  44083. (function (BABYLON) {
  44084. var PostProcess = (function () {
  44085. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  44086. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  44087. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  44088. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  44089. if (blockCompilation === void 0) { blockCompilation = false; }
  44090. this.name = name;
  44091. this.width = -1;
  44092. this.height = -1;
  44093. this.autoClear = true;
  44094. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  44095. /*
  44096. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  44097. Can only be used on a single postprocess or on the last one of a chain.
  44098. */
  44099. this.enablePixelPerfectMode = false;
  44100. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  44101. this.alwaysForcePOT = false;
  44102. this.samples = 1;
  44103. this._reusable = false;
  44104. this._textures = new BABYLON.SmartArray(2);
  44105. this._currentRenderTextureInd = 0;
  44106. this._scaleRatio = new BABYLON.Vector2(1, 1);
  44107. this._texelSize = BABYLON.Vector2.Zero();
  44108. // Events
  44109. /**
  44110. * An event triggered when the postprocess is activated.
  44111. * @type {BABYLON.Observable}
  44112. */
  44113. this.onActivateObservable = new BABYLON.Observable();
  44114. /**
  44115. * An event triggered when the postprocess changes its size.
  44116. * @type {BABYLON.Observable}
  44117. */
  44118. this.onSizeChangedObservable = new BABYLON.Observable();
  44119. /**
  44120. * An event triggered when the postprocess applies its effect.
  44121. * @type {BABYLON.Observable}
  44122. */
  44123. this.onApplyObservable = new BABYLON.Observable();
  44124. /**
  44125. * An event triggered before rendering the postprocess
  44126. * @type {BABYLON.Observable}
  44127. */
  44128. this.onBeforeRenderObservable = new BABYLON.Observable();
  44129. /**
  44130. * An event triggered after rendering the postprocess
  44131. * @type {BABYLON.Observable}
  44132. */
  44133. this.onAfterRenderObservable = new BABYLON.Observable();
  44134. if (camera != null) {
  44135. this._camera = camera;
  44136. this._scene = camera.getScene();
  44137. camera.attachPostProcess(this);
  44138. this._engine = this._scene.getEngine();
  44139. }
  44140. else {
  44141. this._engine = engine;
  44142. }
  44143. this._options = options;
  44144. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  44145. this._reusable = reusable || false;
  44146. this._textureType = textureType;
  44147. this._samplers = samplers || [];
  44148. this._samplers.push("textureSampler");
  44149. this._fragmentUrl = fragmentUrl;
  44150. this._vertexUrl = vertexUrl;
  44151. this._parameters = parameters || [];
  44152. this._parameters.push("scale");
  44153. this._indexParameters = indexParameters;
  44154. if (!blockCompilation) {
  44155. this.updateEffect(defines);
  44156. }
  44157. }
  44158. Object.defineProperty(PostProcess.prototype, "onActivate", {
  44159. set: function (callback) {
  44160. if (this._onActivateObserver) {
  44161. this.onActivateObservable.remove(this._onActivateObserver);
  44162. }
  44163. this._onActivateObserver = this.onActivateObservable.add(callback);
  44164. },
  44165. enumerable: true,
  44166. configurable: true
  44167. });
  44168. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  44169. set: function (callback) {
  44170. if (this._onSizeChangedObserver) {
  44171. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  44172. }
  44173. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  44174. },
  44175. enumerable: true,
  44176. configurable: true
  44177. });
  44178. Object.defineProperty(PostProcess.prototype, "onApply", {
  44179. set: function (callback) {
  44180. if (this._onApplyObserver) {
  44181. this.onApplyObservable.remove(this._onApplyObserver);
  44182. }
  44183. this._onApplyObserver = this.onApplyObservable.add(callback);
  44184. },
  44185. enumerable: true,
  44186. configurable: true
  44187. });
  44188. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  44189. set: function (callback) {
  44190. if (this._onBeforeRenderObserver) {
  44191. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  44192. }
  44193. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  44194. },
  44195. enumerable: true,
  44196. configurable: true
  44197. });
  44198. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  44199. set: function (callback) {
  44200. if (this._onAfterRenderObserver) {
  44201. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  44202. }
  44203. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  44204. },
  44205. enumerable: true,
  44206. configurable: true
  44207. });
  44208. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  44209. get: function () {
  44210. return this._textures.data[this._currentRenderTextureInd];
  44211. },
  44212. set: function (value) {
  44213. this._forcedOutputTexture = value;
  44214. },
  44215. enumerable: true,
  44216. configurable: true
  44217. });
  44218. PostProcess.prototype.getCamera = function () {
  44219. return this._camera;
  44220. };
  44221. Object.defineProperty(PostProcess.prototype, "texelSize", {
  44222. get: function () {
  44223. if (this._shareOutputWithPostProcess) {
  44224. return this._shareOutputWithPostProcess.texelSize;
  44225. }
  44226. if (this._forcedOutputTexture) {
  44227. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  44228. }
  44229. return this._texelSize;
  44230. },
  44231. enumerable: true,
  44232. configurable: true
  44233. });
  44234. PostProcess.prototype.getEngine = function () {
  44235. return this._engine;
  44236. };
  44237. PostProcess.prototype.getEffect = function () {
  44238. return this._effect;
  44239. };
  44240. PostProcess.prototype.shareOutputWith = function (postProcess) {
  44241. this._disposeTextures();
  44242. this._shareOutputWithPostProcess = postProcess;
  44243. return this;
  44244. };
  44245. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  44246. 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);
  44247. };
  44248. PostProcess.prototype.isReusable = function () {
  44249. return this._reusable;
  44250. };
  44251. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  44252. PostProcess.prototype.markTextureDirty = function () {
  44253. this.width = -1;
  44254. };
  44255. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  44256. var _this = this;
  44257. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  44258. camera = camera || this._camera;
  44259. var scene = camera.getScene();
  44260. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  44261. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  44262. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  44263. var desiredWidth = this._options.width || requiredWidth;
  44264. var desiredHeight = this._options.height || requiredHeight;
  44265. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  44266. if (!this._options.width) {
  44267. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  44268. }
  44269. if (!this._options.height) {
  44270. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  44271. }
  44272. }
  44273. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  44274. if (this._textures.length > 0) {
  44275. for (var i = 0; i < this._textures.length; i++) {
  44276. this._engine._releaseTexture(this._textures.data[i]);
  44277. }
  44278. this._textures.reset();
  44279. }
  44280. this.width = desiredWidth;
  44281. this.height = desiredHeight;
  44282. var textureSize = { width: this.width, height: this.height };
  44283. var textureOptions = {
  44284. generateMipMaps: false,
  44285. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  44286. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  44287. samplingMode: this.renderTargetSamplingMode,
  44288. type: this._textureType
  44289. };
  44290. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  44291. if (this._reusable) {
  44292. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  44293. }
  44294. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  44295. this.onSizeChangedObservable.notifyObservers(this);
  44296. }
  44297. this._textures.forEach(function (texture) {
  44298. if (texture.samples !== _this.samples) {
  44299. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  44300. }
  44301. });
  44302. }
  44303. var target;
  44304. if (this._shareOutputWithPostProcess) {
  44305. target = this._shareOutputWithPostProcess.outputTexture;
  44306. }
  44307. else if (this._forcedOutputTexture) {
  44308. target = this._forcedOutputTexture;
  44309. this.width = this._forcedOutputTexture._width;
  44310. this.height = this._forcedOutputTexture._height;
  44311. }
  44312. else {
  44313. target = this.outputTexture;
  44314. }
  44315. if (this.enablePixelPerfectMode) {
  44316. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  44317. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  44318. }
  44319. else {
  44320. this._scaleRatio.copyFromFloats(1, 1);
  44321. this._engine.bindFramebuffer(target);
  44322. }
  44323. this.onActivateObservable.notifyObservers(camera);
  44324. // Clear
  44325. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  44326. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  44327. }
  44328. if (this._reusable) {
  44329. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  44330. }
  44331. };
  44332. Object.defineProperty(PostProcess.prototype, "isSupported", {
  44333. get: function () {
  44334. return this._effect.isSupported;
  44335. },
  44336. enumerable: true,
  44337. configurable: true
  44338. });
  44339. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  44340. get: function () {
  44341. if (this._shareOutputWithPostProcess) {
  44342. return this._shareOutputWithPostProcess.aspectRatio;
  44343. }
  44344. if (this._forcedOutputTexture) {
  44345. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  44346. }
  44347. return this.width / this.height;
  44348. },
  44349. enumerable: true,
  44350. configurable: true
  44351. });
  44352. PostProcess.prototype.apply = function () {
  44353. // Check
  44354. if (!this._effect || !this._effect.isReady())
  44355. return null;
  44356. // States
  44357. this._engine.enableEffect(this._effect);
  44358. this._engine.setState(false);
  44359. this._engine.setDepthBuffer(false);
  44360. this._engine.setDepthWrite(false);
  44361. // Alpha
  44362. this._engine.setAlphaMode(this.alphaMode);
  44363. if (this.alphaConstants) {
  44364. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  44365. }
  44366. // Texture
  44367. var source;
  44368. if (this._shareOutputWithPostProcess) {
  44369. source = this._shareOutputWithPostProcess.outputTexture;
  44370. }
  44371. else if (this._forcedOutputTexture) {
  44372. source = this._forcedOutputTexture;
  44373. }
  44374. else {
  44375. source = this.outputTexture;
  44376. }
  44377. this._effect._bindTexture("textureSampler", source);
  44378. // Parameters
  44379. this._effect.setVector2("scale", this._scaleRatio);
  44380. this.onApplyObservable.notifyObservers(this._effect);
  44381. return this._effect;
  44382. };
  44383. PostProcess.prototype._disposeTextures = function () {
  44384. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  44385. return;
  44386. }
  44387. if (this._textures.length > 0) {
  44388. for (var i = 0; i < this._textures.length; i++) {
  44389. this._engine._releaseTexture(this._textures.data[i]);
  44390. }
  44391. }
  44392. this._textures.dispose();
  44393. };
  44394. PostProcess.prototype.dispose = function (camera) {
  44395. camera = camera || this._camera;
  44396. this._disposeTextures();
  44397. if (!camera) {
  44398. return;
  44399. }
  44400. camera.detachPostProcess(this);
  44401. var index = camera._postProcesses.indexOf(this);
  44402. if (index === 0 && camera._postProcesses.length > 0) {
  44403. this._camera._postProcesses[0].markTextureDirty();
  44404. }
  44405. this.onActivateObservable.clear();
  44406. this.onAfterRenderObservable.clear();
  44407. this.onApplyObservable.clear();
  44408. this.onBeforeRenderObservable.clear();
  44409. this.onSizeChangedObservable.clear();
  44410. };
  44411. return PostProcess;
  44412. }());
  44413. BABYLON.PostProcess = PostProcess;
  44414. })(BABYLON || (BABYLON = {}));
  44415. //# sourceMappingURL=babylon.postProcess.js.map
  44416. var BABYLON;
  44417. (function (BABYLON) {
  44418. var PassPostProcess = (function (_super) {
  44419. __extends(PassPostProcess, _super);
  44420. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  44421. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  44422. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  44423. }
  44424. return PassPostProcess;
  44425. }(BABYLON.PostProcess));
  44426. BABYLON.PassPostProcess = PassPostProcess;
  44427. })(BABYLON || (BABYLON = {}));
  44428. //# sourceMappingURL=babylon.passPostProcess.js.map
  44429. var BABYLON;
  44430. (function (BABYLON) {
  44431. var ShadowGenerator = (function () {
  44432. /**
  44433. * Creates a ShadowGenerator object.
  44434. * A ShadowGenerator is the required tool to use the shadows.
  44435. * Each light casting shadows needs to use its own ShadowGenerator.
  44436. * Required parameters :
  44437. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  44438. * - `light`: the light object generating the shadows.
  44439. * - `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.
  44440. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  44441. */
  44442. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  44443. // Members
  44444. this._bias = 0.00005;
  44445. this._blurBoxOffset = 1;
  44446. this._blurScale = 2;
  44447. this._blurKernel = 1;
  44448. this._useKernelBlur = false;
  44449. this._filter = ShadowGenerator.FILTER_NONE;
  44450. this._darkness = 0;
  44451. this._transparencyShadow = false;
  44452. this.forceBackFacesOnly = false;
  44453. this._lightDirection = BABYLON.Vector3.Zero();
  44454. this._viewMatrix = BABYLON.Matrix.Zero();
  44455. this._projectionMatrix = BABYLON.Matrix.Zero();
  44456. this._transformMatrix = BABYLON.Matrix.Zero();
  44457. this._worldViewProjection = BABYLON.Matrix.Zero();
  44458. this._currentFaceIndex = 0;
  44459. this._currentFaceIndexCache = 0;
  44460. this._isCube = false;
  44461. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  44462. this._mapSize = mapSize;
  44463. this._light = light;
  44464. this._scene = light.getScene();
  44465. light._shadowGenerator = this;
  44466. // Texture type fallback from float to int if not supported.
  44467. var caps = this._scene.getEngine().getCaps();
  44468. if (!useFullFloatFirst) {
  44469. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  44470. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  44471. }
  44472. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  44473. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44474. }
  44475. else {
  44476. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44477. }
  44478. }
  44479. else {
  44480. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  44481. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44482. }
  44483. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  44484. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  44485. }
  44486. else {
  44487. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44488. }
  44489. }
  44490. this._initializeGenerator();
  44491. }
  44492. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  44493. // Static
  44494. get: function () {
  44495. return ShadowGenerator._FILTER_NONE;
  44496. },
  44497. enumerable: true,
  44498. configurable: true
  44499. });
  44500. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  44501. get: function () {
  44502. return ShadowGenerator._FILTER_POISSONSAMPLING;
  44503. },
  44504. enumerable: true,
  44505. configurable: true
  44506. });
  44507. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  44508. get: function () {
  44509. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  44510. },
  44511. enumerable: true,
  44512. configurable: true
  44513. });
  44514. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  44515. get: function () {
  44516. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  44517. },
  44518. enumerable: true,
  44519. configurable: true
  44520. });
  44521. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  44522. get: function () {
  44523. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  44524. },
  44525. enumerable: true,
  44526. configurable: true
  44527. });
  44528. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  44529. get: function () {
  44530. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  44531. },
  44532. enumerable: true,
  44533. configurable: true
  44534. });
  44535. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  44536. get: function () {
  44537. return this._bias;
  44538. },
  44539. set: function (bias) {
  44540. this._bias = bias;
  44541. },
  44542. enumerable: true,
  44543. configurable: true
  44544. });
  44545. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  44546. get: function () {
  44547. return this._blurBoxOffset;
  44548. },
  44549. set: function (value) {
  44550. if (this._blurBoxOffset === value) {
  44551. return;
  44552. }
  44553. this._blurBoxOffset = value;
  44554. this._disposeBlurPostProcesses();
  44555. },
  44556. enumerable: true,
  44557. configurable: true
  44558. });
  44559. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  44560. get: function () {
  44561. return this._blurScale;
  44562. },
  44563. set: function (value) {
  44564. if (this._blurScale === value) {
  44565. return;
  44566. }
  44567. this._blurScale = value;
  44568. this._disposeBlurPostProcesses();
  44569. },
  44570. enumerable: true,
  44571. configurable: true
  44572. });
  44573. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  44574. get: function () {
  44575. return this._blurKernel;
  44576. },
  44577. set: function (value) {
  44578. if (this._blurKernel === value) {
  44579. return;
  44580. }
  44581. this._blurKernel = value;
  44582. this._disposeBlurPostProcesses();
  44583. },
  44584. enumerable: true,
  44585. configurable: true
  44586. });
  44587. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  44588. get: function () {
  44589. return this._useKernelBlur;
  44590. },
  44591. set: function (value) {
  44592. if (this._useKernelBlur === value) {
  44593. return;
  44594. }
  44595. this._useKernelBlur = value;
  44596. this._disposeBlurPostProcesses();
  44597. },
  44598. enumerable: true,
  44599. configurable: true
  44600. });
  44601. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  44602. get: function () {
  44603. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  44604. },
  44605. set: function (value) {
  44606. this._depthScale = value;
  44607. },
  44608. enumerable: true,
  44609. configurable: true
  44610. });
  44611. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  44612. get: function () {
  44613. return this._filter;
  44614. },
  44615. set: function (value) {
  44616. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  44617. if (this._light.needCube()) {
  44618. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  44619. this.useExponentialShadowMap = true;
  44620. return;
  44621. }
  44622. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  44623. this.useCloseExponentialShadowMap = true;
  44624. return;
  44625. }
  44626. }
  44627. if (this._filter === value) {
  44628. return;
  44629. }
  44630. this._filter = value;
  44631. this._disposeBlurPostProcesses();
  44632. this._applyFilterValues();
  44633. this._light._markMeshesAsLightDirty();
  44634. },
  44635. enumerable: true,
  44636. configurable: true
  44637. });
  44638. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  44639. get: function () {
  44640. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  44641. },
  44642. set: function (value) {
  44643. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  44644. },
  44645. enumerable: true,
  44646. configurable: true
  44647. });
  44648. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  44649. get: function () {
  44650. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  44651. return this.useExponentialShadowMap;
  44652. },
  44653. set: function (value) {
  44654. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  44655. this.useExponentialShadowMap = value;
  44656. },
  44657. enumerable: true,
  44658. configurable: true
  44659. });
  44660. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  44661. get: function () {
  44662. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  44663. return this.useBlurExponentialShadowMap;
  44664. },
  44665. set: function (value) {
  44666. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  44667. this.useBlurExponentialShadowMap = value;
  44668. },
  44669. enumerable: true,
  44670. configurable: true
  44671. });
  44672. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  44673. get: function () {
  44674. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  44675. },
  44676. set: function (value) {
  44677. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44678. },
  44679. enumerable: true,
  44680. configurable: true
  44681. });
  44682. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  44683. get: function () {
  44684. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  44685. },
  44686. set: function (value) {
  44687. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44688. },
  44689. enumerable: true,
  44690. configurable: true
  44691. });
  44692. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  44693. get: function () {
  44694. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  44695. },
  44696. set: function (value) {
  44697. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44698. },
  44699. enumerable: true,
  44700. configurable: true
  44701. });
  44702. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  44703. get: function () {
  44704. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  44705. },
  44706. set: function (value) {
  44707. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44708. },
  44709. enumerable: true,
  44710. configurable: true
  44711. });
  44712. /**
  44713. * Returns the darkness value (float).
  44714. */
  44715. ShadowGenerator.prototype.getDarkness = function () {
  44716. return this._darkness;
  44717. };
  44718. /**
  44719. * Sets the ShadowGenerator darkness value (float <= 1.0).
  44720. * Returns the ShadowGenerator.
  44721. */
  44722. ShadowGenerator.prototype.setDarkness = function (darkness) {
  44723. if (darkness >= 1.0)
  44724. this._darkness = 1.0;
  44725. else if (darkness <= 0.0)
  44726. this._darkness = 0.0;
  44727. else
  44728. this._darkness = darkness;
  44729. return this;
  44730. };
  44731. /**
  44732. * Sets the ability to have transparent shadow (boolean).
  44733. * Returns the ShadowGenerator.
  44734. */
  44735. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  44736. this._transparencyShadow = hasShadow;
  44737. return this;
  44738. };
  44739. /**
  44740. * Returns a RenderTargetTexture object : the shadow map texture.
  44741. */
  44742. ShadowGenerator.prototype.getShadowMap = function () {
  44743. return this._shadowMap;
  44744. };
  44745. /**
  44746. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  44747. */
  44748. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  44749. if (this._shadowMap2) {
  44750. return this._shadowMap2;
  44751. }
  44752. return this._shadowMap;
  44753. };
  44754. /**
  44755. * Returns the associated light object.
  44756. */
  44757. ShadowGenerator.prototype.getLight = function () {
  44758. return this._light;
  44759. };
  44760. ShadowGenerator.prototype._initializeGenerator = function () {
  44761. this._light._markMeshesAsLightDirty();
  44762. this._initializeShadowMap();
  44763. };
  44764. ShadowGenerator.prototype._initializeShadowMap = function () {
  44765. var _this = this;
  44766. // Render target
  44767. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  44768. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44769. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44770. this._shadowMap.anisotropicFilteringLevel = 1;
  44771. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44772. this._shadowMap.renderParticles = false;
  44773. // Record Face Index before render.
  44774. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  44775. _this._currentFaceIndex = faceIndex;
  44776. });
  44777. // Custom render function.
  44778. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  44779. // Blur if required afer render.
  44780. this._shadowMap.onAfterUnbindObservable.add(function () {
  44781. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  44782. return;
  44783. }
  44784. if (!_this._blurPostProcesses) {
  44785. _this._initializeBlurRTTAndPostProcesses();
  44786. }
  44787. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  44788. });
  44789. // Clear according to the chosen filter.
  44790. this._shadowMap.onClearObservable.add(function (engine) {
  44791. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  44792. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  44793. }
  44794. else {
  44795. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  44796. }
  44797. });
  44798. };
  44799. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  44800. var _this = this;
  44801. var engine = this._scene.getEngine();
  44802. var targetSize = this._mapSize / this.blurScale;
  44803. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  44804. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  44805. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44806. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44807. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44808. }
  44809. if (this.useKernelBlur) {
  44810. 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);
  44811. this._kernelBlurXPostprocess.width = targetSize;
  44812. this._kernelBlurXPostprocess.height = targetSize;
  44813. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  44814. effect.setTexture("textureSampler", _this._shadowMap);
  44815. });
  44816. 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);
  44817. this._kernelBlurXPostprocess.autoClear = false;
  44818. this._kernelBlurYPostprocess.autoClear = false;
  44819. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44820. this._kernelBlurXPostprocess.packedFloat = true;
  44821. this._kernelBlurYPostprocess.packedFloat = true;
  44822. }
  44823. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  44824. }
  44825. else {
  44826. 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);
  44827. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  44828. effect.setFloat2("screenSize", targetSize, targetSize);
  44829. effect.setTexture("textureSampler", _this._shadowMap);
  44830. });
  44831. this._boxBlurPostprocess.autoClear = false;
  44832. this._blurPostProcesses = [this._boxBlurPostprocess];
  44833. }
  44834. };
  44835. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  44836. var index;
  44837. for (index = 0; index < opaqueSubMeshes.length; index++) {
  44838. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  44839. }
  44840. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  44841. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  44842. }
  44843. if (this._transparencyShadow) {
  44844. for (index = 0; index < transparentSubMeshes.length; index++) {
  44845. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  44846. }
  44847. }
  44848. };
  44849. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  44850. var _this = this;
  44851. var mesh = subMesh.getRenderingMesh();
  44852. var scene = this._scene;
  44853. var engine = scene.getEngine();
  44854. // Culling
  44855. engine.setState(subMesh.getMaterial().backFaceCulling);
  44856. // Managing instances
  44857. var batch = mesh._getInstancesRenderList(subMesh._id);
  44858. if (batch.mustReturn) {
  44859. return;
  44860. }
  44861. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44862. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  44863. engine.enableEffect(this._effect);
  44864. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  44865. var material = subMesh.getMaterial();
  44866. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  44867. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  44868. this._effect.setVector3("lightPosition", this.getLight().position);
  44869. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  44870. // Alpha test
  44871. if (material && material.needAlphaTesting()) {
  44872. var alphaTexture = material.getAlphaTestTexture();
  44873. if (alphaTexture) {
  44874. this._effect.setTexture("diffuseSampler", alphaTexture);
  44875. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  44876. }
  44877. }
  44878. // Bones
  44879. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44880. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44881. }
  44882. if (this.forceBackFacesOnly) {
  44883. engine.setState(true, 0, false, true);
  44884. }
  44885. // Draw
  44886. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  44887. if (this.forceBackFacesOnly) {
  44888. engine.setState(true, 0, false, false);
  44889. }
  44890. }
  44891. else {
  44892. // Need to reset refresh rate of the shadowMap
  44893. this._shadowMap.resetRefreshCounter();
  44894. }
  44895. };
  44896. ShadowGenerator.prototype._applyFilterValues = function () {
  44897. if (this.filter === ShadowGenerator.FILTER_NONE) {
  44898. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  44899. }
  44900. else {
  44901. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44902. }
  44903. };
  44904. /**
  44905. * Boolean : true when the ShadowGenerator is finally computed.
  44906. */
  44907. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  44908. var defines = [];
  44909. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44910. defines.push("#define FLOAT");
  44911. }
  44912. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  44913. defines.push("#define ESM");
  44914. }
  44915. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44916. var mesh = subMesh.getMesh();
  44917. var material = subMesh.getMaterial();
  44918. // Alpha test
  44919. if (material && material.needAlphaTesting()) {
  44920. var alphaTexture = material.getAlphaTestTexture();
  44921. if (alphaTexture) {
  44922. defines.push("#define ALPHATEST");
  44923. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44924. attribs.push(BABYLON.VertexBuffer.UVKind);
  44925. defines.push("#define UV1");
  44926. }
  44927. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44928. if (alphaTexture.coordinatesIndex === 1) {
  44929. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44930. defines.push("#define UV2");
  44931. }
  44932. }
  44933. }
  44934. }
  44935. // Bones
  44936. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44937. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44938. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44939. if (mesh.numBoneInfluencers > 4) {
  44940. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44941. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44942. }
  44943. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44944. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44945. }
  44946. else {
  44947. defines.push("#define NUM_BONE_INFLUENCERS 0");
  44948. }
  44949. // Instances
  44950. if (useInstances) {
  44951. defines.push("#define INSTANCES");
  44952. attribs.push("world0");
  44953. attribs.push("world1");
  44954. attribs.push("world2");
  44955. attribs.push("world3");
  44956. }
  44957. // Get correct effect
  44958. var join = defines.join("\n");
  44959. if (this._cachedDefines !== join) {
  44960. this._cachedDefines = join;
  44961. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  44962. }
  44963. return this._effect.isReady();
  44964. };
  44965. /**
  44966. * This creates the defines related to the standard BJS materials.
  44967. */
  44968. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  44969. var scene = this._scene;
  44970. var light = this._light;
  44971. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  44972. return;
  44973. }
  44974. defines["SHADOW" + lightIndex] = true;
  44975. if (this.usePoissonSampling) {
  44976. defines["SHADOWPCF" + lightIndex] = true;
  44977. }
  44978. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  44979. defines["SHADOWESM" + lightIndex] = true;
  44980. }
  44981. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  44982. defines["SHADOWCLOSEESM" + lightIndex] = true;
  44983. }
  44984. if (light.needCube()) {
  44985. defines["SHADOWCUBE" + lightIndex] = true;
  44986. }
  44987. };
  44988. /**
  44989. * This binds shadow lights related to the standard BJS materials.
  44990. * It implies the unifroms available on the materials are the standard BJS ones.
  44991. */
  44992. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  44993. var light = this._light;
  44994. var scene = this._scene;
  44995. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  44996. return;
  44997. }
  44998. if (!light.needCube()) {
  44999. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  45000. }
  45001. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  45002. light._uniformBuffer.updateFloat3("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, lightIndex);
  45003. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  45004. };
  45005. // Methods
  45006. /**
  45007. * Returns a Matrix object : the updated transformation matrix.
  45008. */
  45009. ShadowGenerator.prototype.getTransformMatrix = function () {
  45010. var scene = this._scene;
  45011. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  45012. return this._transformMatrix;
  45013. }
  45014. this._currentRenderID = scene.getRenderId();
  45015. this._currentFaceIndexCache = this._currentFaceIndex;
  45016. var lightPosition = this._light.position;
  45017. if (this._light.computeTransformedInformation()) {
  45018. lightPosition = this._light.transformedPosition;
  45019. }
  45020. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  45021. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  45022. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  45023. }
  45024. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  45025. this._cachedPosition = lightPosition.clone();
  45026. this._cachedDirection = this._lightDirection.clone();
  45027. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  45028. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  45029. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  45030. }
  45031. return this._transformMatrix;
  45032. };
  45033. ShadowGenerator.prototype.recreateShadowMap = function () {
  45034. // Track render list.
  45035. var renderList = this._shadowMap.renderList;
  45036. // Clean up existing data.
  45037. this._disposeRTTandPostProcesses();
  45038. // Reinitializes.
  45039. this._initializeGenerator();
  45040. // Reaffect the filter to ensure a correct fallback if necessary.
  45041. this.filter = this.filter;
  45042. // Reaffect the filter.
  45043. this._applyFilterValues();
  45044. // Reaffect Render List.
  45045. this._shadowMap.renderList = renderList;
  45046. };
  45047. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  45048. if (this._shadowMap2) {
  45049. this._shadowMap2.dispose();
  45050. this._shadowMap2 = null;
  45051. }
  45052. if (this._downSamplePostprocess) {
  45053. this._downSamplePostprocess.dispose();
  45054. this._downSamplePostprocess = null;
  45055. }
  45056. if (this._boxBlurPostprocess) {
  45057. this._boxBlurPostprocess.dispose();
  45058. this._boxBlurPostprocess = null;
  45059. }
  45060. if (this._kernelBlurXPostprocess) {
  45061. this._kernelBlurXPostprocess.dispose();
  45062. this._kernelBlurXPostprocess = null;
  45063. }
  45064. if (this._kernelBlurYPostprocess) {
  45065. this._kernelBlurYPostprocess.dispose();
  45066. this._kernelBlurYPostprocess = null;
  45067. }
  45068. this._blurPostProcesses = null;
  45069. };
  45070. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  45071. if (this._shadowMap) {
  45072. this._shadowMap.dispose();
  45073. this._shadowMap = null;
  45074. }
  45075. this._disposeBlurPostProcesses();
  45076. };
  45077. /**
  45078. * Disposes the ShadowGenerator.
  45079. * Returns nothing.
  45080. */
  45081. ShadowGenerator.prototype.dispose = function () {
  45082. this._disposeRTTandPostProcesses();
  45083. this._light._shadowGenerator = null;
  45084. this._light._markMeshesAsLightDirty();
  45085. };
  45086. /**
  45087. * Serializes the ShadowGenerator and returns a serializationObject.
  45088. */
  45089. ShadowGenerator.prototype.serialize = function () {
  45090. var serializationObject = {};
  45091. var shadowMap = this.getShadowMap();
  45092. serializationObject.lightId = this._light.id;
  45093. serializationObject.mapSize = shadowMap.getRenderSize();
  45094. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  45095. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  45096. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  45097. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  45098. serializationObject.usePoissonSampling = this.usePoissonSampling;
  45099. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  45100. serializationObject.depthScale = this.depthScale;
  45101. serializationObject.darkness = this.getDarkness();
  45102. serializationObject.blurBoxOffset = this.blurBoxOffset;
  45103. serializationObject.blurKernel = this.blurKernel;
  45104. serializationObject.blurScale = this.blurScale;
  45105. serializationObject.useKernelBlur = this.useKernelBlur;
  45106. serializationObject.transparencyShadow = this._transparencyShadow;
  45107. serializationObject.renderList = [];
  45108. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  45109. var mesh = shadowMap.renderList[meshIndex];
  45110. serializationObject.renderList.push(mesh.id);
  45111. }
  45112. return serializationObject;
  45113. };
  45114. /**
  45115. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  45116. */
  45117. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  45118. //casting to point light, as light is missing the position attr and typescript complains.
  45119. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  45120. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  45121. var shadowMap = shadowGenerator.getShadowMap();
  45122. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  45123. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  45124. meshes.forEach(function (mesh) {
  45125. shadowMap.renderList.push(mesh);
  45126. });
  45127. }
  45128. if (parsedShadowGenerator.usePoissonSampling) {
  45129. shadowGenerator.usePoissonSampling = true;
  45130. }
  45131. else if (parsedShadowGenerator.useExponentialShadowMap) {
  45132. shadowGenerator.useExponentialShadowMap = true;
  45133. }
  45134. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  45135. shadowGenerator.useBlurExponentialShadowMap = true;
  45136. }
  45137. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  45138. shadowGenerator.useCloseExponentialShadowMap = true;
  45139. }
  45140. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  45141. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  45142. }
  45143. else if (parsedShadowGenerator.useVarianceShadowMap) {
  45144. shadowGenerator.useExponentialShadowMap = true;
  45145. }
  45146. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  45147. shadowGenerator.useBlurExponentialShadowMap = true;
  45148. }
  45149. if (parsedShadowGenerator.depthScale) {
  45150. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  45151. }
  45152. if (parsedShadowGenerator.blurScale) {
  45153. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  45154. }
  45155. if (parsedShadowGenerator.blurBoxOffset) {
  45156. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  45157. }
  45158. if (parsedShadowGenerator.useKernelBlur) {
  45159. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  45160. }
  45161. if (parsedShadowGenerator.blurKernel) {
  45162. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  45163. }
  45164. if (parsedShadowGenerator.bias !== undefined) {
  45165. shadowGenerator.bias = parsedShadowGenerator.bias;
  45166. }
  45167. if (parsedShadowGenerator.darkness) {
  45168. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  45169. }
  45170. if (parsedShadowGenerator.transparencyShadow) {
  45171. shadowGenerator.setTransparencyShadow(true);
  45172. }
  45173. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  45174. return shadowGenerator;
  45175. };
  45176. return ShadowGenerator;
  45177. }());
  45178. ShadowGenerator._FILTER_NONE = 0;
  45179. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  45180. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  45181. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  45182. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  45183. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  45184. BABYLON.ShadowGenerator = ShadowGenerator;
  45185. })(BABYLON || (BABYLON = {}));
  45186. //# sourceMappingURL=babylon.shadowGenerator.js.map
  45187. var BABYLON;
  45188. (function (BABYLON) {
  45189. var DefaultLoadingScreen = (function () {
  45190. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  45191. if (_loadingText === void 0) { _loadingText = ""; }
  45192. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  45193. var _this = this;
  45194. this._renderingCanvas = _renderingCanvas;
  45195. this._loadingText = _loadingText;
  45196. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  45197. // Resize
  45198. this._resizeLoadingUI = function () {
  45199. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  45200. _this._loadingDiv.style.position = "absolute";
  45201. _this._loadingDiv.style.left = canvasRect.left + "px";
  45202. _this._loadingDiv.style.top = canvasRect.top + "px";
  45203. _this._loadingDiv.style.width = canvasRect.width + "px";
  45204. _this._loadingDiv.style.height = canvasRect.height + "px";
  45205. };
  45206. }
  45207. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  45208. if (this._loadingDiv) {
  45209. // Do not add a loading screen if there is already one
  45210. return;
  45211. }
  45212. this._loadingDiv = document.createElement("div");
  45213. this._loadingDiv.id = "babylonjsLoadingDiv";
  45214. this._loadingDiv.style.opacity = "0";
  45215. this._loadingDiv.style.transition = "opacity 1.5s ease";
  45216. // Loading text
  45217. this._loadingTextDiv = document.createElement("div");
  45218. this._loadingTextDiv.style.position = "absolute";
  45219. this._loadingTextDiv.style.left = "0";
  45220. this._loadingTextDiv.style.top = "50%";
  45221. this._loadingTextDiv.style.marginTop = "80px";
  45222. this._loadingTextDiv.style.width = "100%";
  45223. this._loadingTextDiv.style.height = "20px";
  45224. this._loadingTextDiv.style.fontFamily = "Arial";
  45225. this._loadingTextDiv.style.fontSize = "14px";
  45226. this._loadingTextDiv.style.color = "white";
  45227. this._loadingTextDiv.style.textAlign = "center";
  45228. this._loadingTextDiv.innerHTML = "Loading";
  45229. this._loadingDiv.appendChild(this._loadingTextDiv);
  45230. //set the predefined text
  45231. this._loadingTextDiv.innerHTML = this._loadingText;
  45232. // Generating keyframes
  45233. var style = document.createElement('style');
  45234. style.type = 'text/css';
  45235. 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 }";
  45236. style.innerHTML = keyFrames;
  45237. document.getElementsByTagName('head')[0].appendChild(style);
  45238. // Loading img
  45239. var imgBack = new Image();
  45240. 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";
  45241. imgBack.style.position = "absolute";
  45242. imgBack.style.left = "50%";
  45243. imgBack.style.top = "50%";
  45244. imgBack.style.marginLeft = "-50px";
  45245. imgBack.style.marginTop = "-50px";
  45246. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  45247. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  45248. imgBack.style.transformOrigin = "50% 50%";
  45249. imgBack.style.webkitTransformOrigin = "50% 50%";
  45250. this._loadingDiv.appendChild(imgBack);
  45251. this._resizeLoadingUI();
  45252. window.addEventListener("resize", this._resizeLoadingUI);
  45253. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  45254. document.body.appendChild(this._loadingDiv);
  45255. this._loadingDiv.style.opacity = "1";
  45256. };
  45257. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  45258. var _this = this;
  45259. if (!this._loadingDiv) {
  45260. return;
  45261. }
  45262. var onTransitionEnd = function () {
  45263. if (!_this._loadingDiv) {
  45264. return;
  45265. }
  45266. document.body.removeChild(_this._loadingDiv);
  45267. window.removeEventListener("resize", _this._resizeLoadingUI);
  45268. _this._loadingDiv = null;
  45269. };
  45270. this._loadingDiv.style.opacity = "0";
  45271. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  45272. };
  45273. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  45274. set: function (text) {
  45275. this._loadingText = text;
  45276. if (this._loadingTextDiv) {
  45277. this._loadingTextDiv.innerHTML = this._loadingText;
  45278. }
  45279. },
  45280. enumerable: true,
  45281. configurable: true
  45282. });
  45283. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  45284. get: function () {
  45285. return this._loadingDivBackgroundColor;
  45286. },
  45287. set: function (color) {
  45288. this._loadingDivBackgroundColor = color;
  45289. if (!this._loadingDiv) {
  45290. return;
  45291. }
  45292. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  45293. },
  45294. enumerable: true,
  45295. configurable: true
  45296. });
  45297. return DefaultLoadingScreen;
  45298. }());
  45299. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  45300. })(BABYLON || (BABYLON = {}));
  45301. //# sourceMappingURL=babylon.loadingScreen.js.map
  45302. var BABYLON;
  45303. (function (BABYLON) {
  45304. var SceneLoader = (function () {
  45305. function SceneLoader() {
  45306. }
  45307. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  45308. get: function () {
  45309. return 0;
  45310. },
  45311. enumerable: true,
  45312. configurable: true
  45313. });
  45314. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  45315. get: function () {
  45316. return 1;
  45317. },
  45318. enumerable: true,
  45319. configurable: true
  45320. });
  45321. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  45322. get: function () {
  45323. return 2;
  45324. },
  45325. enumerable: true,
  45326. configurable: true
  45327. });
  45328. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  45329. get: function () {
  45330. return 3;
  45331. },
  45332. enumerable: true,
  45333. configurable: true
  45334. });
  45335. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  45336. get: function () {
  45337. return SceneLoader._ForceFullSceneLoadingForIncremental;
  45338. },
  45339. set: function (value) {
  45340. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  45341. },
  45342. enumerable: true,
  45343. configurable: true
  45344. });
  45345. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  45346. get: function () {
  45347. return SceneLoader._ShowLoadingScreen;
  45348. },
  45349. set: function (value) {
  45350. SceneLoader._ShowLoadingScreen = value;
  45351. },
  45352. enumerable: true,
  45353. configurable: true
  45354. });
  45355. Object.defineProperty(SceneLoader, "loggingLevel", {
  45356. get: function () {
  45357. return SceneLoader._loggingLevel;
  45358. },
  45359. set: function (value) {
  45360. SceneLoader._loggingLevel = value;
  45361. },
  45362. enumerable: true,
  45363. configurable: true
  45364. });
  45365. SceneLoader._getDefaultPlugin = function () {
  45366. return SceneLoader._registeredPlugins[".babylon"];
  45367. };
  45368. SceneLoader._getPluginForExtension = function (extension) {
  45369. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  45370. if (registeredPlugin) {
  45371. return registeredPlugin;
  45372. }
  45373. return SceneLoader._getDefaultPlugin();
  45374. };
  45375. SceneLoader._getPluginForDirectLoad = function (data) {
  45376. for (var extension in SceneLoader._registeredPlugins) {
  45377. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  45378. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  45379. return SceneLoader._registeredPlugins[extension];
  45380. }
  45381. }
  45382. return SceneLoader._getDefaultPlugin();
  45383. };
  45384. SceneLoader._getPluginForFilename = function (sceneFilename) {
  45385. if (sceneFilename.name) {
  45386. sceneFilename = sceneFilename.name;
  45387. }
  45388. var dotPosition = sceneFilename.lastIndexOf(".");
  45389. var queryStringPosition = sceneFilename.indexOf("?");
  45390. if (queryStringPosition === -1) {
  45391. queryStringPosition = sceneFilename.length;
  45392. }
  45393. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  45394. return SceneLoader._getPluginForExtension(extension);
  45395. };
  45396. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  45397. SceneLoader._getDirectLoad = function (sceneFilename) {
  45398. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  45399. return sceneFilename.substr(5);
  45400. }
  45401. return null;
  45402. };
  45403. // Public functions
  45404. SceneLoader.GetPluginForExtension = function (extension) {
  45405. return SceneLoader._getPluginForExtension(extension).plugin;
  45406. };
  45407. SceneLoader.RegisterPlugin = function (plugin) {
  45408. if (typeof plugin.extensions === "string") {
  45409. var extension = plugin.extensions;
  45410. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  45411. plugin: plugin,
  45412. isBinary: false
  45413. };
  45414. }
  45415. else {
  45416. var extensions = plugin.extensions;
  45417. Object.keys(extensions).forEach(function (extension) {
  45418. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  45419. plugin: plugin,
  45420. isBinary: extensions[extension].isBinary
  45421. };
  45422. });
  45423. }
  45424. };
  45425. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  45426. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  45427. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  45428. return;
  45429. }
  45430. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  45431. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  45432. return;
  45433. }
  45434. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  45435. var loadingToken = {};
  45436. scene._addPendingData(loadingToken);
  45437. var manifestChecked = function (success) {
  45438. scene.database = database;
  45439. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(directLoad) : SceneLoader._getPluginForFilename(sceneFilename);
  45440. var plugin = registeredPlugin.plugin;
  45441. var useArrayBuffer = registeredPlugin.isBinary;
  45442. var importMeshFromData = function (data) {
  45443. var meshes = [];
  45444. var particleSystems = [];
  45445. var skeletons = [];
  45446. if (scene.isDisposed) {
  45447. if (onerror) {
  45448. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  45449. }
  45450. return;
  45451. }
  45452. try {
  45453. if (plugin.importMesh) {
  45454. var syncedPlugin = plugin;
  45455. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  45456. if (onerror) {
  45457. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  45458. }
  45459. scene._removePendingData(loadingToken);
  45460. return;
  45461. }
  45462. if (onsuccess) {
  45463. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  45464. onsuccess(meshes, particleSystems, skeletons);
  45465. scene._removePendingData(loadingToken);
  45466. }
  45467. }
  45468. else {
  45469. var asyncedPlugin = plugin;
  45470. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  45471. if (onsuccess) {
  45472. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  45473. onsuccess(meshes, particleSystems, skeletons);
  45474. scene._removePendingData(loadingToken);
  45475. }
  45476. }, function () {
  45477. if (onerror) {
  45478. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  45479. }
  45480. scene._removePendingData(loadingToken);
  45481. });
  45482. }
  45483. }
  45484. catch (e) {
  45485. if (onerror) {
  45486. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  45487. }
  45488. scene._removePendingData(loadingToken);
  45489. }
  45490. };
  45491. if (directLoad) {
  45492. importMeshFromData(directLoad);
  45493. return;
  45494. }
  45495. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  45496. importMeshFromData(data);
  45497. }, progressCallBack, database, useArrayBuffer, function () {
  45498. if (onerror) {
  45499. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  45500. }
  45501. });
  45502. };
  45503. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  45504. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  45505. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  45506. }
  45507. else {
  45508. // If the scene is a data stream or offline support is not enabled, it's a direct load
  45509. manifestChecked(true);
  45510. }
  45511. };
  45512. /**
  45513. * Load a scene
  45514. * @param rootUrl a string that defines the root url for scene and resources
  45515. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  45516. * @param engine is the instance of BABYLON.Engine to use to create the scene
  45517. */
  45518. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  45519. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  45520. };
  45521. /**
  45522. * Append a scene
  45523. * @param rootUrl a string that defines the root url for scene and resources
  45524. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  45525. * @param scene is the instance of BABYLON.Scene to append to
  45526. */
  45527. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  45528. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  45529. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  45530. return;
  45531. }
  45532. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  45533. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  45534. var plugin = registeredPlugin.plugin;
  45535. var useArrayBuffer = registeredPlugin.isBinary;
  45536. var database;
  45537. var loadingToken = {};
  45538. scene._addPendingData(loadingToken);
  45539. if (SceneLoader.ShowLoadingScreen) {
  45540. scene.getEngine().displayLoadingUI();
  45541. }
  45542. var loadSceneFromData = function (data) {
  45543. scene.database = database;
  45544. if (plugin.load) {
  45545. var syncedPlugin = plugin;
  45546. if (!syncedPlugin.load(scene, data, rootUrl)) {
  45547. if (onerror) {
  45548. onerror(scene);
  45549. }
  45550. scene._removePendingData(loadingToken);
  45551. scene.getEngine().hideLoadingUI();
  45552. return;
  45553. }
  45554. if (onsuccess) {
  45555. onsuccess(scene);
  45556. }
  45557. scene._removePendingData(loadingToken);
  45558. }
  45559. else {
  45560. var asyncedPlugin = plugin;
  45561. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  45562. if (onsuccess) {
  45563. onsuccess(scene);
  45564. }
  45565. scene._removePendingData(loadingToken);
  45566. }, function () {
  45567. if (onerror) {
  45568. onerror(scene);
  45569. }
  45570. scene._removePendingData(loadingToken);
  45571. scene.getEngine().hideLoadingUI();
  45572. });
  45573. }
  45574. if (SceneLoader.ShowLoadingScreen) {
  45575. scene.executeWhenReady(function () {
  45576. scene.getEngine().hideLoadingUI();
  45577. });
  45578. }
  45579. };
  45580. var manifestChecked = function (success) {
  45581. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  45582. };
  45583. if (directLoad) {
  45584. loadSceneFromData(directLoad);
  45585. return;
  45586. }
  45587. if (rootUrl.indexOf("file:") === -1) {
  45588. if (scene.getEngine().enableOfflineSupport) {
  45589. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  45590. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  45591. }
  45592. else {
  45593. manifestChecked(true);
  45594. }
  45595. }
  45596. else {
  45597. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  45598. }
  45599. };
  45600. return SceneLoader;
  45601. }());
  45602. // Flags
  45603. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  45604. SceneLoader._ShowLoadingScreen = true;
  45605. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  45606. // Members
  45607. SceneLoader._registeredPlugins = {};
  45608. BABYLON.SceneLoader = SceneLoader;
  45609. ;
  45610. })(BABYLON || (BABYLON = {}));
  45611. //# sourceMappingURL=babylon.sceneLoader.js.map
  45612. var BABYLON;
  45613. (function (BABYLON) {
  45614. var Internals;
  45615. (function (Internals) {
  45616. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  45617. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  45618. var parsedMaterial = parsedData.materials[index];
  45619. if (parsedMaterial.id === id) {
  45620. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  45621. }
  45622. }
  45623. return null;
  45624. };
  45625. var isDescendantOf = function (mesh, names, hierarchyIds) {
  45626. names = (names instanceof Array) ? names : [names];
  45627. for (var i in names) {
  45628. if (mesh.name === names[i]) {
  45629. hierarchyIds.push(mesh.id);
  45630. return true;
  45631. }
  45632. }
  45633. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  45634. hierarchyIds.push(mesh.id);
  45635. return true;
  45636. }
  45637. return false;
  45638. };
  45639. var logOperation = function (operation, producer) {
  45640. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  45641. };
  45642. BABYLON.SceneLoader.RegisterPlugin({
  45643. extensions: ".babylon",
  45644. canDirectLoad: function (data) {
  45645. if (data.indexOf("babylon") !== -1) {
  45646. return true;
  45647. }
  45648. return false;
  45649. },
  45650. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  45651. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  45652. // when SceneLoader.debugLogging = true (default), or exception encountered.
  45653. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  45654. // and avoid problems with multiple concurrent .babylon loads.
  45655. var log = "importMesh has failed JSON parse";
  45656. try {
  45657. var parsedData = JSON.parse(data);
  45658. log = "";
  45659. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  45660. var loadedSkeletonsIds = [];
  45661. var loadedMaterialsIds = [];
  45662. var hierarchyIds = [];
  45663. var index;
  45664. var cache;
  45665. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  45666. var parsedMesh = parsedData.meshes[index];
  45667. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  45668. if (meshesNames instanceof Array) {
  45669. // Remove found mesh name from list.
  45670. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  45671. }
  45672. //Geometry?
  45673. if (parsedMesh.geometryId) {
  45674. //does the file contain geometries?
  45675. if (parsedData.geometries) {
  45676. //find the correct geometry and add it to the scene
  45677. var found = false;
  45678. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  45679. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  45680. return;
  45681. }
  45682. else {
  45683. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  45684. if (parsedGeometryData.id === parsedMesh.geometryId) {
  45685. switch (geometryType) {
  45686. case "boxes":
  45687. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  45688. break;
  45689. case "spheres":
  45690. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  45691. break;
  45692. case "cylinders":
  45693. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  45694. break;
  45695. case "toruses":
  45696. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  45697. break;
  45698. case "grounds":
  45699. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  45700. break;
  45701. case "planes":
  45702. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  45703. break;
  45704. case "torusKnots":
  45705. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  45706. break;
  45707. case "vertexData":
  45708. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  45709. break;
  45710. }
  45711. found = true;
  45712. }
  45713. });
  45714. }
  45715. });
  45716. if (!found) {
  45717. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  45718. }
  45719. }
  45720. }
  45721. // Material ?
  45722. if (parsedMesh.materialId) {
  45723. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  45724. if (!materialFound && parsedData.multiMaterials) {
  45725. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  45726. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  45727. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  45728. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  45729. var subMatId = parsedMultiMaterial.materials[matIndex];
  45730. loadedMaterialsIds.push(subMatId);
  45731. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  45732. log += "\n\tMaterial " + mat.toString(fullDetails);
  45733. }
  45734. loadedMaterialsIds.push(parsedMultiMaterial.id);
  45735. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  45736. materialFound = true;
  45737. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  45738. break;
  45739. }
  45740. }
  45741. }
  45742. if (!materialFound) {
  45743. loadedMaterialsIds.push(parsedMesh.materialId);
  45744. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  45745. if (!mat) {
  45746. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  45747. }
  45748. else {
  45749. log += "\n\tMaterial " + mat.toString(fullDetails);
  45750. }
  45751. }
  45752. }
  45753. // Skeleton ?
  45754. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  45755. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  45756. if (!skeletonAlreadyLoaded) {
  45757. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  45758. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  45759. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  45760. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  45761. skeletons.push(skeleton);
  45762. loadedSkeletonsIds.push(parsedSkeleton.id);
  45763. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  45764. }
  45765. }
  45766. }
  45767. }
  45768. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  45769. meshes.push(mesh);
  45770. log += "\n\tMesh " + mesh.toString(fullDetails);
  45771. }
  45772. }
  45773. // Connecting parents
  45774. var currentMesh;
  45775. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45776. currentMesh = scene.meshes[index];
  45777. if (currentMesh._waitingParentId) {
  45778. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  45779. currentMesh._waitingParentId = undefined;
  45780. }
  45781. }
  45782. // freeze and compute world matrix application
  45783. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45784. currentMesh = scene.meshes[index];
  45785. if (currentMesh._waitingFreezeWorldMatrix) {
  45786. currentMesh.freezeWorldMatrix();
  45787. currentMesh._waitingFreezeWorldMatrix = undefined;
  45788. }
  45789. else {
  45790. currentMesh.computeWorldMatrix(true);
  45791. }
  45792. }
  45793. // Particles
  45794. if (parsedData.particleSystems) {
  45795. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  45796. var parsedParticleSystem = parsedData.particleSystems[index];
  45797. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  45798. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  45799. }
  45800. }
  45801. }
  45802. return true;
  45803. }
  45804. catch (err) {
  45805. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  45806. log = null;
  45807. throw err;
  45808. }
  45809. finally {
  45810. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  45811. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  45812. }
  45813. }
  45814. },
  45815. load: function (scene, data, rootUrl) {
  45816. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  45817. // when SceneLoader.debugLogging = true (default), or exception encountered.
  45818. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  45819. // and avoid problems with multiple concurrent .babylon loads.
  45820. var log = "importScene has failed JSON parse";
  45821. try {
  45822. var parsedData = JSON.parse(data);
  45823. log = "";
  45824. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  45825. // Scene
  45826. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  45827. scene.autoClear = parsedData.autoClear;
  45828. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  45829. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  45830. if (parsedData.gravity) {
  45831. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  45832. }
  45833. // Fog
  45834. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  45835. scene.fogMode = parsedData.fogMode;
  45836. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  45837. scene.fogStart = parsedData.fogStart;
  45838. scene.fogEnd = parsedData.fogEnd;
  45839. scene.fogDensity = parsedData.fogDensity;
  45840. log += "\tFog mode for scene: ";
  45841. switch (scene.fogMode) {
  45842. // getters not compiling, so using hardcoded
  45843. case 1:
  45844. log += "exp\n";
  45845. break;
  45846. case 2:
  45847. log += "exp2\n";
  45848. break;
  45849. case 3:
  45850. log += "linear\n";
  45851. break;
  45852. }
  45853. }
  45854. //Physics
  45855. if (parsedData.physicsEnabled) {
  45856. var physicsPlugin;
  45857. if (parsedData.physicsEngine === "cannon") {
  45858. physicsPlugin = new BABYLON.CannonJSPlugin();
  45859. }
  45860. else if (parsedData.physicsEngine === "oimo") {
  45861. physicsPlugin = new BABYLON.OimoJSPlugin();
  45862. }
  45863. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  45864. //else - default engine, which is currently oimo
  45865. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  45866. scene.enablePhysics(physicsGravity, physicsPlugin);
  45867. }
  45868. // Metadata
  45869. if (parsedData.metadata !== undefined) {
  45870. scene.metadata = parsedData.metadata;
  45871. }
  45872. //collisions, if defined. otherwise, default is true
  45873. if (parsedData.collisionsEnabled != undefined) {
  45874. scene.collisionsEnabled = parsedData.collisionsEnabled;
  45875. }
  45876. scene.workerCollisions = !!parsedData.workerCollisions;
  45877. var index;
  45878. var cache;
  45879. // Lights
  45880. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  45881. var parsedLight = parsedData.lights[index];
  45882. var light = BABYLON.Light.Parse(parsedLight, scene);
  45883. log += (index === 0 ? "\n\tLights:" : "");
  45884. log += "\n\t\t" + light.toString(fullDetails);
  45885. }
  45886. // Animations
  45887. if (parsedData.animations) {
  45888. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  45889. var parsedAnimation = parsedData.animations[index];
  45890. var animation = BABYLON.Animation.Parse(parsedAnimation);
  45891. scene.animations.push(animation);
  45892. log += (index === 0 ? "\n\tAnimations:" : "");
  45893. log += "\n\t\t" + animation.toString(fullDetails);
  45894. }
  45895. }
  45896. if (parsedData.autoAnimate) {
  45897. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  45898. }
  45899. // Materials
  45900. if (parsedData.materials) {
  45901. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  45902. var parsedMaterial = parsedData.materials[index];
  45903. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  45904. log += (index === 0 ? "\n\tMaterials:" : "");
  45905. log += "\n\t\t" + mat.toString(fullDetails);
  45906. }
  45907. }
  45908. if (parsedData.multiMaterials) {
  45909. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  45910. var parsedMultiMaterial = parsedData.multiMaterials[index];
  45911. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  45912. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  45913. log += "\n\t\t" + mmat.toString(fullDetails);
  45914. }
  45915. }
  45916. // Morph targets
  45917. if (parsedData.morphTargetManagers) {
  45918. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  45919. var managerData = _a[_i];
  45920. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  45921. }
  45922. }
  45923. // Skeletons
  45924. if (parsedData.skeletons) {
  45925. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  45926. var parsedSkeleton = parsedData.skeletons[index];
  45927. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  45928. log += (index === 0 ? "\n\tSkeletons:" : "");
  45929. log += "\n\t\t" + skeleton.toString(fullDetails);
  45930. }
  45931. }
  45932. // Geometries
  45933. var geometries = parsedData.geometries;
  45934. if (geometries) {
  45935. // Boxes
  45936. var boxes = geometries.boxes;
  45937. if (boxes) {
  45938. for (index = 0, cache = boxes.length; index < cache; index++) {
  45939. var parsedBox = boxes[index];
  45940. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  45941. }
  45942. }
  45943. // Spheres
  45944. var spheres = geometries.spheres;
  45945. if (spheres) {
  45946. for (index = 0, cache = spheres.length; index < cache; index++) {
  45947. var parsedSphere = spheres[index];
  45948. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  45949. }
  45950. }
  45951. // Cylinders
  45952. var cylinders = geometries.cylinders;
  45953. if (cylinders) {
  45954. for (index = 0, cache = cylinders.length; index < cache; index++) {
  45955. var parsedCylinder = cylinders[index];
  45956. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  45957. }
  45958. }
  45959. // Toruses
  45960. var toruses = geometries.toruses;
  45961. if (toruses) {
  45962. for (index = 0, cache = toruses.length; index < cache; index++) {
  45963. var parsedTorus = toruses[index];
  45964. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  45965. }
  45966. }
  45967. // Grounds
  45968. var grounds = geometries.grounds;
  45969. if (grounds) {
  45970. for (index = 0, cache = grounds.length; index < cache; index++) {
  45971. var parsedGround = grounds[index];
  45972. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  45973. }
  45974. }
  45975. // Planes
  45976. var planes = geometries.planes;
  45977. if (planes) {
  45978. for (index = 0, cache = planes.length; index < cache; index++) {
  45979. var parsedPlane = planes[index];
  45980. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  45981. }
  45982. }
  45983. // TorusKnots
  45984. var torusKnots = geometries.torusKnots;
  45985. if (torusKnots) {
  45986. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  45987. var parsedTorusKnot = torusKnots[index];
  45988. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  45989. }
  45990. }
  45991. // VertexData
  45992. var vertexData = geometries.vertexData;
  45993. if (vertexData) {
  45994. for (index = 0, cache = vertexData.length; index < cache; index++) {
  45995. var parsedVertexData = vertexData[index];
  45996. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  45997. }
  45998. }
  45999. }
  46000. // Meshes
  46001. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  46002. var parsedMesh = parsedData.meshes[index];
  46003. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  46004. log += (index === 0 ? "\n\tMeshes:" : "");
  46005. log += "\n\t\t" + mesh.toString(fullDetails);
  46006. }
  46007. // Cameras
  46008. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  46009. var parsedCamera = parsedData.cameras[index];
  46010. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  46011. log += (index === 0 ? "\n\tCameras:" : "");
  46012. log += "\n\t\t" + camera.toString(fullDetails);
  46013. }
  46014. if (parsedData.activeCameraID) {
  46015. scene.setActiveCameraByID(parsedData.activeCameraID);
  46016. }
  46017. // Browsing all the graph to connect the dots
  46018. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  46019. var camera = scene.cameras[index];
  46020. if (camera._waitingParentId) {
  46021. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  46022. camera._waitingParentId = undefined;
  46023. }
  46024. }
  46025. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  46026. var light = scene.lights[index];
  46027. if (light._waitingParentId) {
  46028. light.parent = scene.getLastEntryByID(light._waitingParentId);
  46029. light._waitingParentId = undefined;
  46030. }
  46031. }
  46032. // Sounds
  46033. var loadedSounds = [];
  46034. var loadedSound;
  46035. if (BABYLON.AudioEngine && parsedData.sounds) {
  46036. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  46037. var parsedSound = parsedData.sounds[index];
  46038. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46039. if (!parsedSound.url)
  46040. parsedSound.url = parsedSound.name;
  46041. if (!loadedSounds[parsedSound.url]) {
  46042. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  46043. loadedSounds[parsedSound.url] = loadedSound;
  46044. }
  46045. else {
  46046. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  46047. }
  46048. }
  46049. else {
  46050. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  46051. }
  46052. }
  46053. }
  46054. loadedSounds = [];
  46055. // Connect parents & children and parse actions
  46056. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  46057. var mesh = scene.meshes[index];
  46058. if (mesh._waitingParentId) {
  46059. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  46060. mesh._waitingParentId = undefined;
  46061. }
  46062. if (mesh._waitingActions) {
  46063. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  46064. mesh._waitingActions = undefined;
  46065. }
  46066. }
  46067. // freeze world matrix application
  46068. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  46069. var currentMesh = scene.meshes[index];
  46070. if (currentMesh._waitingFreezeWorldMatrix) {
  46071. currentMesh.freezeWorldMatrix();
  46072. currentMesh._waitingFreezeWorldMatrix = undefined;
  46073. }
  46074. else {
  46075. currentMesh.computeWorldMatrix(true);
  46076. }
  46077. }
  46078. // Particles Systems
  46079. if (parsedData.particleSystems) {
  46080. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  46081. var parsedParticleSystem = parsedData.particleSystems[index];
  46082. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  46083. }
  46084. }
  46085. // Lens flares
  46086. if (parsedData.lensFlareSystems) {
  46087. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  46088. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  46089. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  46090. }
  46091. }
  46092. // Shadows
  46093. if (parsedData.shadowGenerators) {
  46094. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  46095. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  46096. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  46097. }
  46098. }
  46099. // Lights exclusions / inclusions
  46100. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  46101. var light = scene.lights[index];
  46102. // Excluded check
  46103. if (light._excludedMeshesIds.length > 0) {
  46104. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  46105. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  46106. if (excludedMesh) {
  46107. light.excludedMeshes.push(excludedMesh);
  46108. }
  46109. }
  46110. light._excludedMeshesIds = [];
  46111. }
  46112. // Included check
  46113. if (light._includedOnlyMeshesIds.length > 0) {
  46114. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  46115. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  46116. if (includedOnlyMesh) {
  46117. light.includedOnlyMeshes.push(includedOnlyMesh);
  46118. }
  46119. }
  46120. light._includedOnlyMeshesIds = [];
  46121. }
  46122. }
  46123. // Actions (scene)
  46124. if (parsedData.actions) {
  46125. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  46126. }
  46127. // Finish
  46128. return true;
  46129. }
  46130. catch (err) {
  46131. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  46132. log = null;
  46133. throw err;
  46134. }
  46135. finally {
  46136. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  46137. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  46138. }
  46139. }
  46140. }
  46141. });
  46142. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46143. })(BABYLON || (BABYLON = {}));
  46144. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  46145. var BABYLON;
  46146. (function (BABYLON) {
  46147. var FilesInput = (function () {
  46148. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  46149. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  46150. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  46151. this._engine = p_engine;
  46152. this._canvas = p_canvas;
  46153. this._currentScene = p_scene;
  46154. this._sceneLoadedCallback = p_sceneLoadedCallback;
  46155. this._progressCallback = p_progressCallback;
  46156. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  46157. this._textureLoadingCallback = p_textureLoadingCallback;
  46158. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  46159. }
  46160. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  46161. var _this = this;
  46162. if (p_elementToMonitor) {
  46163. this._elementToMonitor = p_elementToMonitor;
  46164. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  46165. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  46166. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  46167. }
  46168. };
  46169. FilesInput.prototype.renderFunction = function () {
  46170. if (this._additionnalRenderLoopLogicCallback) {
  46171. this._additionnalRenderLoopLogicCallback();
  46172. }
  46173. if (this._currentScene) {
  46174. if (this._textureLoadingCallback) {
  46175. var remaining = this._currentScene.getWaitingItemsCount();
  46176. if (remaining > 0) {
  46177. this._textureLoadingCallback(remaining);
  46178. }
  46179. }
  46180. this._currentScene.render();
  46181. }
  46182. };
  46183. FilesInput.prototype.drag = function (e) {
  46184. e.stopPropagation();
  46185. e.preventDefault();
  46186. };
  46187. FilesInput.prototype.drop = function (eventDrop) {
  46188. eventDrop.stopPropagation();
  46189. eventDrop.preventDefault();
  46190. this.loadFiles(eventDrop);
  46191. };
  46192. FilesInput.prototype.loadFiles = function (event) {
  46193. if (this._startingProcessingFilesCallback)
  46194. this._startingProcessingFilesCallback();
  46195. // Handling data transfer via drag'n'drop
  46196. if (event && event.dataTransfer && event.dataTransfer.files) {
  46197. this._filesToLoad = event.dataTransfer.files;
  46198. }
  46199. // Handling files from input files
  46200. if (event && event.target && event.target.files) {
  46201. this._filesToLoad = event.target.files;
  46202. }
  46203. if (this._filesToLoad && this._filesToLoad.length > 0) {
  46204. for (var i = 0; i < this._filesToLoad.length; i++) {
  46205. var name_1 = this._filesToLoad[i].name.toLowerCase();
  46206. var extension = name_1.split('.').pop();
  46207. var type = this._filesToLoad[i].type;
  46208. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  46209. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  46210. this._sceneFileToLoad = this._filesToLoad[i];
  46211. }
  46212. else {
  46213. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  46214. }
  46215. }
  46216. this.reload();
  46217. }
  46218. };
  46219. FilesInput.prototype.reload = function () {
  46220. var _this = this;
  46221. var that = this;
  46222. // If a ".babylon" file has been provided
  46223. if (this._sceneFileToLoad) {
  46224. if (this._currentScene) {
  46225. if (BABYLON.Tools.errorsCount > 0) {
  46226. BABYLON.Tools.ClearLogCache();
  46227. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  46228. }
  46229. this._engine.stopRenderLoop();
  46230. this._currentScene.dispose();
  46231. }
  46232. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  46233. that._currentScene = newScene;
  46234. // Wait for textures and shaders to be ready
  46235. that._currentScene.executeWhenReady(function () {
  46236. if (that._sceneLoadedCallback) {
  46237. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  46238. }
  46239. that._engine.runRenderLoop(function () { that.renderFunction(); });
  46240. });
  46241. }, function (progress) {
  46242. if (_this._progressCallback) {
  46243. _this._progressCallback(progress);
  46244. }
  46245. });
  46246. }
  46247. else {
  46248. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  46249. }
  46250. };
  46251. return FilesInput;
  46252. }());
  46253. FilesInput.FilesToLoad = new Array();
  46254. BABYLON.FilesInput = FilesInput;
  46255. })(BABYLON || (BABYLON = {}));
  46256. //# sourceMappingURL=babylon.filesInput.js.map
  46257. var BABYLON;
  46258. (function (BABYLON) {
  46259. /**
  46260. * This class implement a typical dictionary using a string as key and the generic type T as value.
  46261. * The underlying implementation relies on an associative array to ensure the best performances.
  46262. * The value can be anything including 'null' but except 'undefined'
  46263. */
  46264. var StringDictionary = (function () {
  46265. function StringDictionary() {
  46266. this._count = 0;
  46267. this._data = {};
  46268. }
  46269. /**
  46270. * This will clear this dictionary and copy the content from the 'source' one.
  46271. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  46272. * @param source the dictionary to take the content from and copy to this dictionary
  46273. */
  46274. StringDictionary.prototype.copyFrom = function (source) {
  46275. var _this = this;
  46276. this.clear();
  46277. source.forEach(function (t, v) { return _this.add(t, v); });
  46278. };
  46279. /**
  46280. * Get a value based from its key
  46281. * @param key the given key to get the matching value from
  46282. * @return the value if found, otherwise undefined is returned
  46283. */
  46284. StringDictionary.prototype.get = function (key) {
  46285. var val = this._data[key];
  46286. if (val !== undefined) {
  46287. return val;
  46288. }
  46289. return undefined;
  46290. };
  46291. /**
  46292. * Get a value from its key or add it if it doesn't exist.
  46293. * This method will ensure you that a given key/data will be present in the dictionary.
  46294. * @param key the given key to get the matching value from
  46295. * @param factory the factory that will create the value if the key is not present in the dictionary.
  46296. * The factory will only be invoked if there's no data for the given key.
  46297. * @return the value corresponding to the key.
  46298. */
  46299. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  46300. var val = this.get(key);
  46301. if (val !== undefined) {
  46302. return val;
  46303. }
  46304. val = factory(key);
  46305. if (val) {
  46306. this.add(key, val);
  46307. }
  46308. return val;
  46309. };
  46310. /**
  46311. * Get a value from its key if present in the dictionary otherwise add it
  46312. * @param key the key to get the value from
  46313. * @param val if there's no such key/value pair in the dictionary add it with this value
  46314. * @return the value corresponding to the key
  46315. */
  46316. StringDictionary.prototype.getOrAdd = function (key, val) {
  46317. var curVal = this.get(key);
  46318. if (curVal !== undefined) {
  46319. return curVal;
  46320. }
  46321. this.add(key, val);
  46322. return val;
  46323. };
  46324. /**
  46325. * Check if there's a given key in the dictionary
  46326. * @param key the key to check for
  46327. * @return true if the key is present, false otherwise
  46328. */
  46329. StringDictionary.prototype.contains = function (key) {
  46330. return this._data[key] !== undefined;
  46331. };
  46332. /**
  46333. * Add a new key and its corresponding value
  46334. * @param key the key to add
  46335. * @param value the value corresponding to the key
  46336. * @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
  46337. */
  46338. StringDictionary.prototype.add = function (key, value) {
  46339. if (this._data[key] !== undefined) {
  46340. return false;
  46341. }
  46342. this._data[key] = value;
  46343. ++this._count;
  46344. return true;
  46345. };
  46346. StringDictionary.prototype.set = function (key, value) {
  46347. if (this._data[key] === undefined) {
  46348. return false;
  46349. }
  46350. this._data[key] = value;
  46351. return true;
  46352. };
  46353. /**
  46354. * Get the element of the given key and remove it from the dictionary
  46355. * @param key
  46356. */
  46357. StringDictionary.prototype.getAndRemove = function (key) {
  46358. var val = this.get(key);
  46359. if (val !== undefined) {
  46360. delete this._data[key];
  46361. --this._count;
  46362. return val;
  46363. }
  46364. return null;
  46365. };
  46366. /**
  46367. * Remove a key/value from the dictionary.
  46368. * @param key the key to remove
  46369. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  46370. */
  46371. StringDictionary.prototype.remove = function (key) {
  46372. if (this.contains(key)) {
  46373. delete this._data[key];
  46374. --this._count;
  46375. return true;
  46376. }
  46377. return false;
  46378. };
  46379. /**
  46380. * Clear the whole content of the dictionary
  46381. */
  46382. StringDictionary.prototype.clear = function () {
  46383. this._data = {};
  46384. this._count = 0;
  46385. };
  46386. Object.defineProperty(StringDictionary.prototype, "count", {
  46387. get: function () {
  46388. return this._count;
  46389. },
  46390. enumerable: true,
  46391. configurable: true
  46392. });
  46393. /**
  46394. * Execute a callback on each key/val of the dictionary.
  46395. * Note that you can remove any element in this dictionary in the callback implementation
  46396. * @param callback the callback to execute on a given key/value pair
  46397. */
  46398. StringDictionary.prototype.forEach = function (callback) {
  46399. for (var cur in this._data) {
  46400. var val = this._data[cur];
  46401. callback(cur, val);
  46402. }
  46403. };
  46404. /**
  46405. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  46406. * If the callback returns null or undefined the method will iterate to the next key/value pair
  46407. * Note that you can remove any element in this dictionary in the callback implementation
  46408. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  46409. */
  46410. StringDictionary.prototype.first = function (callback) {
  46411. for (var cur in this._data) {
  46412. var val = this._data[cur];
  46413. var res = callback(cur, val);
  46414. if (res) {
  46415. return res;
  46416. }
  46417. }
  46418. return null;
  46419. };
  46420. return StringDictionary;
  46421. }());
  46422. BABYLON.StringDictionary = StringDictionary;
  46423. })(BABYLON || (BABYLON = {}));
  46424. //# sourceMappingURL=babylon.stringDictionary.js.map
  46425. var BABYLON;
  46426. (function (BABYLON) {
  46427. var Tags = (function () {
  46428. function Tags() {
  46429. }
  46430. Tags.EnableFor = function (obj) {
  46431. obj._tags = obj._tags || {};
  46432. obj.hasTags = function () {
  46433. return Tags.HasTags(obj);
  46434. };
  46435. obj.addTags = function (tagsString) {
  46436. return Tags.AddTagsTo(obj, tagsString);
  46437. };
  46438. obj.removeTags = function (tagsString) {
  46439. return Tags.RemoveTagsFrom(obj, tagsString);
  46440. };
  46441. obj.matchesTagsQuery = function (tagsQuery) {
  46442. return Tags.MatchesQuery(obj, tagsQuery);
  46443. };
  46444. };
  46445. Tags.DisableFor = function (obj) {
  46446. delete obj._tags;
  46447. delete obj.hasTags;
  46448. delete obj.addTags;
  46449. delete obj.removeTags;
  46450. delete obj.matchesTagsQuery;
  46451. };
  46452. Tags.HasTags = function (obj) {
  46453. if (!obj._tags) {
  46454. return false;
  46455. }
  46456. return !BABYLON.Tools.IsEmpty(obj._tags);
  46457. };
  46458. Tags.GetTags = function (obj, asString) {
  46459. if (asString === void 0) { asString = true; }
  46460. if (!obj._tags) {
  46461. return null;
  46462. }
  46463. if (asString) {
  46464. var tagsArray = [];
  46465. for (var tag in obj._tags) {
  46466. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  46467. tagsArray.push(tag);
  46468. }
  46469. }
  46470. return tagsArray.join(" ");
  46471. }
  46472. else {
  46473. return obj._tags;
  46474. }
  46475. };
  46476. // the tags 'true' and 'false' are reserved and cannot be used as tags
  46477. // a tag cannot start with '||', '&&', and '!'
  46478. // it cannot contain whitespaces
  46479. Tags.AddTagsTo = function (obj, tagsString) {
  46480. if (!tagsString) {
  46481. return;
  46482. }
  46483. if (typeof tagsString !== "string") {
  46484. return;
  46485. }
  46486. var tags = tagsString.split(" ");
  46487. tags.forEach(function (tag, index, array) {
  46488. Tags._AddTagTo(obj, tag);
  46489. });
  46490. };
  46491. Tags._AddTagTo = function (obj, tag) {
  46492. tag = tag.trim();
  46493. if (tag === "" || tag === "true" || tag === "false") {
  46494. return;
  46495. }
  46496. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  46497. return;
  46498. }
  46499. Tags.EnableFor(obj);
  46500. obj._tags[tag] = true;
  46501. };
  46502. Tags.RemoveTagsFrom = function (obj, tagsString) {
  46503. if (!Tags.HasTags(obj)) {
  46504. return;
  46505. }
  46506. var tags = tagsString.split(" ");
  46507. for (var t in tags) {
  46508. Tags._RemoveTagFrom(obj, tags[t]);
  46509. }
  46510. };
  46511. Tags._RemoveTagFrom = function (obj, tag) {
  46512. delete obj._tags[tag];
  46513. };
  46514. Tags.MatchesQuery = function (obj, tagsQuery) {
  46515. if (tagsQuery === undefined) {
  46516. return true;
  46517. }
  46518. if (tagsQuery === "") {
  46519. return Tags.HasTags(obj);
  46520. }
  46521. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  46522. };
  46523. return Tags;
  46524. }());
  46525. BABYLON.Tags = Tags;
  46526. })(BABYLON || (BABYLON = {}));
  46527. //# sourceMappingURL=babylon.tags.js.map
  46528. var BABYLON;
  46529. (function (BABYLON) {
  46530. var Internals;
  46531. (function (Internals) {
  46532. var AndOrNotEvaluator = (function () {
  46533. function AndOrNotEvaluator() {
  46534. }
  46535. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  46536. if (!query.match(/\([^\(\)]*\)/g)) {
  46537. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  46538. }
  46539. else {
  46540. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  46541. // remove parenthesis
  46542. r = r.slice(1, r.length - 1);
  46543. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  46544. });
  46545. }
  46546. if (query === "true") {
  46547. return true;
  46548. }
  46549. if (query === "false") {
  46550. return false;
  46551. }
  46552. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  46553. };
  46554. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  46555. evaluateCallback = evaluateCallback || (function (r) {
  46556. return r === "true" ? true : false;
  46557. });
  46558. var result;
  46559. var or = parenthesisContent.split("||");
  46560. for (var i in or) {
  46561. if (or.hasOwnProperty(i)) {
  46562. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  46563. var and = ori.split("&&");
  46564. if (and.length > 1) {
  46565. for (var j = 0; j < and.length; ++j) {
  46566. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  46567. if (andj !== "true" && andj !== "false") {
  46568. if (andj[0] === "!") {
  46569. result = !evaluateCallback(andj.substring(1));
  46570. }
  46571. else {
  46572. result = evaluateCallback(andj);
  46573. }
  46574. }
  46575. else {
  46576. result = andj === "true" ? true : false;
  46577. }
  46578. if (!result) {
  46579. ori = "false";
  46580. break;
  46581. }
  46582. }
  46583. }
  46584. if (result || ori === "true") {
  46585. result = true;
  46586. break;
  46587. }
  46588. // result equals false (or undefined)
  46589. if (ori !== "true" && ori !== "false") {
  46590. if (ori[0] === "!") {
  46591. result = !evaluateCallback(ori.substring(1));
  46592. }
  46593. else {
  46594. result = evaluateCallback(ori);
  46595. }
  46596. }
  46597. else {
  46598. result = ori === "true" ? true : false;
  46599. }
  46600. }
  46601. }
  46602. // the whole parenthesis scope is replaced by 'true' or 'false'
  46603. return result ? "true" : "false";
  46604. };
  46605. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  46606. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  46607. // remove whitespaces
  46608. r = r.replace(/[\s]/g, function () { return ""; });
  46609. return r.length % 2 ? "!" : "";
  46610. });
  46611. booleanString = booleanString.trim();
  46612. if (booleanString === "!true") {
  46613. booleanString = "false";
  46614. }
  46615. else if (booleanString === "!false") {
  46616. booleanString = "true";
  46617. }
  46618. return booleanString;
  46619. };
  46620. return AndOrNotEvaluator;
  46621. }());
  46622. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  46623. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46624. })(BABYLON || (BABYLON = {}));
  46625. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  46626. var BABYLON;
  46627. (function (BABYLON) {
  46628. var Database = (function () {
  46629. function Database(urlToScene, callbackManifestChecked) {
  46630. // Handling various flavors of prefixed version of IndexedDB
  46631. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  46632. this.callbackManifestChecked = callbackManifestChecked;
  46633. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  46634. this.db = null;
  46635. this.enableSceneOffline = false;
  46636. this.enableTexturesOffline = false;
  46637. this.manifestVersionFound = 0;
  46638. this.mustUpdateRessources = false;
  46639. this.hasReachedQuota = false;
  46640. if (!Database.IDBStorageEnabled) {
  46641. this.callbackManifestChecked(true);
  46642. }
  46643. else {
  46644. this.checkManifestFile();
  46645. }
  46646. }
  46647. Database.prototype.checkManifestFile = function () {
  46648. var _this = this;
  46649. function noManifestFile() {
  46650. that.enableSceneOffline = false;
  46651. that.enableTexturesOffline = false;
  46652. that.callbackManifestChecked(false);
  46653. }
  46654. var that = this;
  46655. var timeStampUsed = false;
  46656. var manifestURL = this.currentSceneUrl + ".manifest";
  46657. var xhr = new XMLHttpRequest();
  46658. if (navigator.onLine) {
  46659. // Adding a timestamp to by-pass browsers' cache
  46660. timeStampUsed = true;
  46661. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  46662. }
  46663. xhr.open("GET", manifestURL, true);
  46664. xhr.addEventListener("load", function () {
  46665. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  46666. try {
  46667. var manifestFile = JSON.parse(xhr.response);
  46668. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  46669. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  46670. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  46671. _this.manifestVersionFound = manifestFile.version;
  46672. }
  46673. if (_this.callbackManifestChecked) {
  46674. _this.callbackManifestChecked(true);
  46675. }
  46676. }
  46677. catch (ex) {
  46678. noManifestFile();
  46679. }
  46680. }
  46681. else {
  46682. noManifestFile();
  46683. }
  46684. }, false);
  46685. xhr.addEventListener("error", function (event) {
  46686. if (timeStampUsed) {
  46687. timeStampUsed = false;
  46688. // Let's retry without the timeStamp
  46689. // It could fail when coupled with HTML5 Offline API
  46690. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  46691. xhr.open("GET", retryManifestURL, true);
  46692. xhr.send();
  46693. }
  46694. else {
  46695. noManifestFile();
  46696. }
  46697. }, false);
  46698. try {
  46699. xhr.send();
  46700. }
  46701. catch (ex) {
  46702. BABYLON.Tools.Error("Error on XHR send request.");
  46703. that.callbackManifestChecked(false);
  46704. }
  46705. };
  46706. Database.prototype.openAsync = function (successCallback, errorCallback) {
  46707. var _this = this;
  46708. function handleError() {
  46709. that.isSupported = false;
  46710. if (errorCallback)
  46711. errorCallback();
  46712. }
  46713. var that = this;
  46714. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  46715. // Your browser doesn't support IndexedDB
  46716. this.isSupported = false;
  46717. if (errorCallback)
  46718. errorCallback();
  46719. }
  46720. else {
  46721. // If the DB hasn't been opened or created yet
  46722. if (!this.db) {
  46723. this.hasReachedQuota = false;
  46724. this.isSupported = true;
  46725. var request = this.idbFactory.open("babylonjs", 1);
  46726. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  46727. request.onerror = function (event) {
  46728. handleError();
  46729. };
  46730. // executes when a version change transaction cannot complete due to other active transactions
  46731. request.onblocked = function (event) {
  46732. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  46733. handleError();
  46734. };
  46735. // DB has been opened successfully
  46736. request.onsuccess = function (event) {
  46737. _this.db = request.result;
  46738. successCallback();
  46739. };
  46740. // Initialization of the DB. Creating Scenes & Textures stores
  46741. request.onupgradeneeded = function (event) {
  46742. _this.db = (event.target).result;
  46743. try {
  46744. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  46745. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  46746. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  46747. }
  46748. catch (ex) {
  46749. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  46750. handleError();
  46751. }
  46752. };
  46753. }
  46754. else {
  46755. if (successCallback)
  46756. successCallback();
  46757. }
  46758. }
  46759. };
  46760. Database.prototype.loadImageFromDB = function (url, image) {
  46761. var _this = this;
  46762. var completeURL = Database.ReturnFullUrlLocation(url);
  46763. var saveAndLoadImage = function () {
  46764. if (!_this.hasReachedQuota && _this.db !== null) {
  46765. // the texture is not yet in the DB, let's try to save it
  46766. _this._saveImageIntoDBAsync(completeURL, image);
  46767. }
  46768. else {
  46769. image.src = url;
  46770. }
  46771. };
  46772. if (!this.mustUpdateRessources) {
  46773. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  46774. }
  46775. else {
  46776. saveAndLoadImage();
  46777. }
  46778. };
  46779. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  46780. if (this.isSupported && this.db !== null) {
  46781. var texture;
  46782. var transaction = this.db.transaction(["textures"]);
  46783. transaction.onabort = function (event) {
  46784. image.src = url;
  46785. };
  46786. transaction.oncomplete = function (event) {
  46787. var blobTextureURL;
  46788. if (texture) {
  46789. var URL = window.URL || window.webkitURL;
  46790. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  46791. image.onerror = function () {
  46792. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  46793. image.src = url;
  46794. };
  46795. image.src = blobTextureURL;
  46796. }
  46797. else {
  46798. notInDBCallback();
  46799. }
  46800. };
  46801. var getRequest = transaction.objectStore("textures").get(url);
  46802. getRequest.onsuccess = function (event) {
  46803. texture = (event.target).result;
  46804. };
  46805. getRequest.onerror = function (event) {
  46806. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  46807. image.src = url;
  46808. };
  46809. }
  46810. else {
  46811. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46812. image.src = url;
  46813. }
  46814. };
  46815. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  46816. var _this = this;
  46817. if (this.isSupported) {
  46818. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  46819. var generateBlobUrl = function () {
  46820. var blobTextureURL;
  46821. if (blob) {
  46822. var URL = window.URL || window.webkitURL;
  46823. try {
  46824. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  46825. }
  46826. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  46827. catch (ex) {
  46828. blobTextureURL = URL.createObjectURL(blob);
  46829. }
  46830. }
  46831. image.src = blobTextureURL;
  46832. };
  46833. if (Database.IsUASupportingBlobStorage) {
  46834. var xhr = new XMLHttpRequest(), blob;
  46835. xhr.open("GET", url, true);
  46836. xhr.responseType = "blob";
  46837. xhr.addEventListener("load", function () {
  46838. if (xhr.status === 200) {
  46839. // Blob as response (XHR2)
  46840. blob = xhr.response;
  46841. var transaction = _this.db.transaction(["textures"], "readwrite");
  46842. // the transaction could abort because of a QuotaExceededError error
  46843. transaction.onabort = function (event) {
  46844. try {
  46845. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  46846. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  46847. _this.hasReachedQuota = true;
  46848. }
  46849. }
  46850. catch (ex) { }
  46851. generateBlobUrl();
  46852. };
  46853. transaction.oncomplete = function (event) {
  46854. generateBlobUrl();
  46855. };
  46856. var newTexture = { textureUrl: url, data: blob };
  46857. try {
  46858. // Put the blob into the dabase
  46859. var addRequest = transaction.objectStore("textures").put(newTexture);
  46860. addRequest.onsuccess = function (event) {
  46861. };
  46862. addRequest.onerror = function (event) {
  46863. generateBlobUrl();
  46864. };
  46865. }
  46866. catch (ex) {
  46867. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  46868. if (ex.code === 25) {
  46869. Database.IsUASupportingBlobStorage = false;
  46870. }
  46871. image.src = url;
  46872. }
  46873. }
  46874. else {
  46875. image.src = url;
  46876. }
  46877. }, false);
  46878. xhr.addEventListener("error", function (event) {
  46879. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  46880. image.src = url;
  46881. }, false);
  46882. xhr.send();
  46883. }
  46884. else {
  46885. image.src = url;
  46886. }
  46887. }
  46888. else {
  46889. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46890. image.src = url;
  46891. }
  46892. };
  46893. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  46894. var _this = this;
  46895. var updateVersion = function (event) {
  46896. // the version is not yet in the DB or we need to update it
  46897. _this._saveVersionIntoDBAsync(url, versionLoaded);
  46898. };
  46899. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  46900. };
  46901. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  46902. var _this = this;
  46903. if (this.isSupported) {
  46904. var version;
  46905. try {
  46906. var transaction = this.db.transaction(["versions"]);
  46907. transaction.oncomplete = function (event) {
  46908. if (version) {
  46909. // If the version in the JSON file is > than the version in DB
  46910. if (_this.manifestVersionFound > version.data) {
  46911. _this.mustUpdateRessources = true;
  46912. updateInDBCallback();
  46913. }
  46914. else {
  46915. callback(version.data);
  46916. }
  46917. }
  46918. else {
  46919. _this.mustUpdateRessources = true;
  46920. updateInDBCallback();
  46921. }
  46922. };
  46923. transaction.onabort = function (event) {
  46924. callback(-1);
  46925. };
  46926. var getRequest = transaction.objectStore("versions").get(url);
  46927. getRequest.onsuccess = function (event) {
  46928. version = (event.target).result;
  46929. };
  46930. getRequest.onerror = function (event) {
  46931. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  46932. callback(-1);
  46933. };
  46934. }
  46935. catch (ex) {
  46936. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  46937. callback(-1);
  46938. }
  46939. }
  46940. else {
  46941. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46942. callback(-1);
  46943. }
  46944. };
  46945. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  46946. var _this = this;
  46947. if (this.isSupported && !this.hasReachedQuota) {
  46948. try {
  46949. // Open a transaction to the database
  46950. var transaction = this.db.transaction(["versions"], "readwrite");
  46951. // the transaction could abort because of a QuotaExceededError error
  46952. transaction.onabort = function (event) {
  46953. try {
  46954. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  46955. _this.hasReachedQuota = true;
  46956. }
  46957. }
  46958. catch (ex) { }
  46959. callback(-1);
  46960. };
  46961. transaction.oncomplete = function (event) {
  46962. callback(_this.manifestVersionFound);
  46963. };
  46964. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  46965. // Put the scene into the database
  46966. var addRequest = transaction.objectStore("versions").put(newVersion);
  46967. addRequest.onsuccess = function (event) {
  46968. };
  46969. addRequest.onerror = function (event) {
  46970. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  46971. };
  46972. }
  46973. catch (ex) {
  46974. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  46975. callback(-1);
  46976. }
  46977. }
  46978. else {
  46979. callback(-1);
  46980. }
  46981. };
  46982. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  46983. var _this = this;
  46984. var completeUrl = Database.ReturnFullUrlLocation(url);
  46985. var saveAndLoadFile = function (event) {
  46986. // the scene is not yet in the DB, let's try to save it
  46987. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  46988. };
  46989. this._checkVersionFromDB(completeUrl, function (version) {
  46990. if (version !== -1) {
  46991. if (!_this.mustUpdateRessources) {
  46992. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  46993. }
  46994. else {
  46995. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  46996. }
  46997. }
  46998. else {
  46999. errorCallback();
  47000. }
  47001. });
  47002. };
  47003. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  47004. if (this.isSupported) {
  47005. var targetStore;
  47006. if (url.indexOf(".babylon") !== -1) {
  47007. targetStore = "scenes";
  47008. }
  47009. else {
  47010. targetStore = "textures";
  47011. }
  47012. var file;
  47013. var transaction = this.db.transaction([targetStore]);
  47014. transaction.oncomplete = function (event) {
  47015. if (file) {
  47016. callback(file.data);
  47017. }
  47018. else {
  47019. notInDBCallback();
  47020. }
  47021. };
  47022. transaction.onabort = function (event) {
  47023. notInDBCallback();
  47024. };
  47025. var getRequest = transaction.objectStore(targetStore).get(url);
  47026. getRequest.onsuccess = function (event) {
  47027. file = (event.target).result;
  47028. };
  47029. getRequest.onerror = function (event) {
  47030. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  47031. notInDBCallback();
  47032. };
  47033. }
  47034. else {
  47035. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  47036. callback();
  47037. }
  47038. };
  47039. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  47040. var _this = this;
  47041. if (this.isSupported) {
  47042. var targetStore;
  47043. if (url.indexOf(".babylon") !== -1) {
  47044. targetStore = "scenes";
  47045. }
  47046. else {
  47047. targetStore = "textures";
  47048. }
  47049. // Create XHR
  47050. var xhr = new XMLHttpRequest(), fileData;
  47051. xhr.open("GET", url, true);
  47052. if (useArrayBuffer) {
  47053. xhr.responseType = "arraybuffer";
  47054. }
  47055. xhr.onprogress = progressCallback;
  47056. xhr.addEventListener("load", function () {
  47057. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  47058. // Blob as response (XHR2)
  47059. //fileData = xhr.responseText;
  47060. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  47061. if (!_this.hasReachedQuota) {
  47062. // Open a transaction to the database
  47063. var transaction = _this.db.transaction([targetStore], "readwrite");
  47064. // the transaction could abort because of a QuotaExceededError error
  47065. transaction.onabort = function (event) {
  47066. try {
  47067. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  47068. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  47069. _this.hasReachedQuota = true;
  47070. }
  47071. }
  47072. catch (ex) { }
  47073. callback(fileData);
  47074. };
  47075. transaction.oncomplete = function (event) {
  47076. callback(fileData);
  47077. };
  47078. var newFile;
  47079. if (targetStore === "scenes") {
  47080. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  47081. }
  47082. else {
  47083. newFile = { textureUrl: url, data: fileData };
  47084. }
  47085. try {
  47086. // Put the scene into the database
  47087. var addRequest = transaction.objectStore(targetStore).put(newFile);
  47088. addRequest.onsuccess = function (event) {
  47089. };
  47090. addRequest.onerror = function (event) {
  47091. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  47092. };
  47093. }
  47094. catch (ex) {
  47095. callback(fileData);
  47096. }
  47097. }
  47098. else {
  47099. callback(fileData);
  47100. }
  47101. }
  47102. else {
  47103. callback();
  47104. }
  47105. }, false);
  47106. xhr.addEventListener("error", function (event) {
  47107. BABYLON.Tools.Error("error on XHR request.");
  47108. callback();
  47109. }, false);
  47110. xhr.send();
  47111. }
  47112. else {
  47113. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  47114. callback();
  47115. }
  47116. };
  47117. return Database;
  47118. }());
  47119. Database.IsUASupportingBlobStorage = true;
  47120. Database.IDBStorageEnabled = true;
  47121. Database.parseURL = function (url) {
  47122. var a = document.createElement('a');
  47123. a.href = url;
  47124. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  47125. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  47126. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  47127. return absLocation;
  47128. };
  47129. Database.ReturnFullUrlLocation = function (url) {
  47130. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  47131. return (Database.parseURL(window.location.href) + url);
  47132. }
  47133. else {
  47134. return url;
  47135. }
  47136. };
  47137. BABYLON.Database = Database;
  47138. })(BABYLON || (BABYLON = {}));
  47139. //# sourceMappingURL=babylon.database.js.map
  47140. var BABYLON;
  47141. (function (BABYLON) {
  47142. var FresnelParameters = (function () {
  47143. function FresnelParameters() {
  47144. this._isEnabled = true;
  47145. this.leftColor = BABYLON.Color3.White();
  47146. this.rightColor = BABYLON.Color3.Black();
  47147. this.bias = 0;
  47148. this.power = 1;
  47149. }
  47150. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  47151. get: function () {
  47152. return this._isEnabled;
  47153. },
  47154. set: function (value) {
  47155. if (this._isEnabled === value) {
  47156. return;
  47157. }
  47158. this._isEnabled = value;
  47159. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  47160. },
  47161. enumerable: true,
  47162. configurable: true
  47163. });
  47164. FresnelParameters.prototype.clone = function () {
  47165. var newFresnelParameters = new FresnelParameters();
  47166. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  47167. return newFresnelParameters;
  47168. };
  47169. FresnelParameters.prototype.serialize = function () {
  47170. var serializationObject = {};
  47171. serializationObject.isEnabled = this.isEnabled;
  47172. serializationObject.leftColor = this.leftColor;
  47173. serializationObject.rightColor = this.rightColor;
  47174. serializationObject.bias = this.bias;
  47175. serializationObject.power = this.power;
  47176. return serializationObject;
  47177. };
  47178. FresnelParameters.Parse = function (parsedFresnelParameters) {
  47179. var fresnelParameters = new FresnelParameters();
  47180. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  47181. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  47182. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  47183. fresnelParameters.bias = parsedFresnelParameters.bias;
  47184. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  47185. return fresnelParameters;
  47186. };
  47187. return FresnelParameters;
  47188. }());
  47189. BABYLON.FresnelParameters = FresnelParameters;
  47190. })(BABYLON || (BABYLON = {}));
  47191. //# sourceMappingURL=babylon.fresnelParameters.js.map
  47192. var BABYLON;
  47193. (function (BABYLON) {
  47194. var MultiMaterial = (function (_super) {
  47195. __extends(MultiMaterial, _super);
  47196. function MultiMaterial(name, scene) {
  47197. var _this = _super.call(this, name, scene, true) || this;
  47198. scene.multiMaterials.push(_this);
  47199. _this.subMaterials = new Array();
  47200. return _this;
  47201. }
  47202. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  47203. get: function () {
  47204. return this._subMaterials;
  47205. },
  47206. set: function (value) {
  47207. this._subMaterials = value;
  47208. this._hookArray(value);
  47209. },
  47210. enumerable: true,
  47211. configurable: true
  47212. });
  47213. MultiMaterial.prototype._hookArray = function (array) {
  47214. var _this = this;
  47215. var oldPush = array.push;
  47216. array.push = function () {
  47217. var items = [];
  47218. for (var _i = 0; _i < arguments.length; _i++) {
  47219. items[_i] = arguments[_i];
  47220. }
  47221. var result = oldPush.apply(array, items);
  47222. _this._markAllSubMeshesAsTexturesDirty();
  47223. return result;
  47224. };
  47225. var oldSplice = array.splice;
  47226. array.splice = function (index, deleteCount) {
  47227. var deleted = oldSplice.apply(array, [index, deleteCount]);
  47228. _this._markAllSubMeshesAsTexturesDirty();
  47229. return deleted;
  47230. };
  47231. };
  47232. // Properties
  47233. MultiMaterial.prototype.getSubMaterial = function (index) {
  47234. if (index < 0 || index >= this.subMaterials.length) {
  47235. return this.getScene().defaultMaterial;
  47236. }
  47237. return this.subMaterials[index];
  47238. };
  47239. MultiMaterial.prototype.getActiveTextures = function () {
  47240. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  47241. var _a;
  47242. };
  47243. // Methods
  47244. MultiMaterial.prototype.getClassName = function () {
  47245. return "MultiMaterial";
  47246. };
  47247. MultiMaterial.prototype.isReady = function (mesh) {
  47248. for (var index = 0; index < this.subMaterials.length; index++) {
  47249. var subMaterial = this.subMaterials[index];
  47250. if (subMaterial) {
  47251. if (!this.subMaterials[index].isReady(mesh)) {
  47252. return false;
  47253. }
  47254. }
  47255. }
  47256. return true;
  47257. };
  47258. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  47259. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  47260. for (var index = 0; index < this.subMaterials.length; index++) {
  47261. var subMaterial = null;
  47262. if (cloneChildren) {
  47263. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  47264. }
  47265. else {
  47266. subMaterial = this.subMaterials[index];
  47267. }
  47268. newMultiMaterial.subMaterials.push(subMaterial);
  47269. }
  47270. return newMultiMaterial;
  47271. };
  47272. MultiMaterial.prototype.serialize = function () {
  47273. var serializationObject = {};
  47274. serializationObject.name = this.name;
  47275. serializationObject.id = this.id;
  47276. serializationObject.tags = BABYLON.Tags.GetTags(this);
  47277. serializationObject.materials = [];
  47278. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  47279. var subMat = this.subMaterials[matIndex];
  47280. if (subMat) {
  47281. serializationObject.materials.push(subMat.id);
  47282. }
  47283. else {
  47284. serializationObject.materials.push(null);
  47285. }
  47286. }
  47287. return serializationObject;
  47288. };
  47289. return MultiMaterial;
  47290. }(BABYLON.Material));
  47291. BABYLON.MultiMaterial = MultiMaterial;
  47292. })(BABYLON || (BABYLON = {}));
  47293. //# sourceMappingURL=babylon.multiMaterial.js.map
  47294. var BABYLON;
  47295. (function (BABYLON) {
  47296. var FreeCameraTouchInput = (function () {
  47297. function FreeCameraTouchInput() {
  47298. this._offsetX = null;
  47299. this._offsetY = null;
  47300. this._pointerCount = 0;
  47301. this._pointerPressed = [];
  47302. this.touchAngularSensibility = 200000.0;
  47303. this.touchMoveSensibility = 250.0;
  47304. }
  47305. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  47306. var _this = this;
  47307. var previousPosition;
  47308. if (this._pointerInput === undefined) {
  47309. this._onLostFocus = function (evt) {
  47310. _this._offsetX = null;
  47311. _this._offsetY = null;
  47312. };
  47313. this._pointerInput = function (p, s) {
  47314. var evt = p.event;
  47315. if (evt.pointerType === "mouse") {
  47316. return;
  47317. }
  47318. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  47319. if (!noPreventDefault) {
  47320. evt.preventDefault();
  47321. }
  47322. _this._pointerPressed.push(evt.pointerId);
  47323. if (_this._pointerPressed.length !== 1) {
  47324. return;
  47325. }
  47326. previousPosition = {
  47327. x: evt.clientX,
  47328. y: evt.clientY
  47329. };
  47330. }
  47331. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  47332. if (!noPreventDefault) {
  47333. evt.preventDefault();
  47334. }
  47335. var index = _this._pointerPressed.indexOf(evt.pointerId);
  47336. if (index === -1) {
  47337. return;
  47338. }
  47339. _this._pointerPressed.splice(index, 1);
  47340. if (index != 0) {
  47341. return;
  47342. }
  47343. previousPosition = null;
  47344. _this._offsetX = null;
  47345. _this._offsetY = null;
  47346. }
  47347. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47348. if (!noPreventDefault) {
  47349. evt.preventDefault();
  47350. }
  47351. if (!previousPosition) {
  47352. return;
  47353. }
  47354. var index = _this._pointerPressed.indexOf(evt.pointerId);
  47355. if (index != 0) {
  47356. return;
  47357. }
  47358. _this._offsetX = evt.clientX - previousPosition.x;
  47359. _this._offsetY = -(evt.clientY - previousPosition.y);
  47360. }
  47361. };
  47362. }
  47363. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47364. element.addEventListener("blur", this._onLostFocus);
  47365. };
  47366. FreeCameraTouchInput.prototype.detachControl = function (element) {
  47367. if (this._pointerInput && element) {
  47368. this.camera.getScene().onPointerObservable.remove(this._observer);
  47369. this._observer = null;
  47370. element.removeEventListener("blur", this._onLostFocus);
  47371. this._onLostFocus = null;
  47372. this._pointerPressed = [];
  47373. this._offsetX = null;
  47374. this._offsetY = null;
  47375. this._pointerCount = 0;
  47376. }
  47377. };
  47378. FreeCameraTouchInput.prototype.checkInputs = function () {
  47379. if (this._offsetX) {
  47380. var camera = this.camera;
  47381. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  47382. if (this._pointerPressed.length > 1) {
  47383. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  47384. }
  47385. else {
  47386. var speed = camera._computeLocalCameraSpeed();
  47387. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  47388. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  47389. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  47390. }
  47391. }
  47392. };
  47393. FreeCameraTouchInput.prototype.getTypeName = function () {
  47394. return "FreeCameraTouchInput";
  47395. };
  47396. FreeCameraTouchInput.prototype.getSimpleName = function () {
  47397. return "touch";
  47398. };
  47399. return FreeCameraTouchInput;
  47400. }());
  47401. __decorate([
  47402. BABYLON.serialize()
  47403. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  47404. __decorate([
  47405. BABYLON.serialize()
  47406. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  47407. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  47408. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  47409. })(BABYLON || (BABYLON = {}));
  47410. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  47411. /// <reference path="babylon.freeCamera.ts" />
  47412. var BABYLON;
  47413. (function (BABYLON) {
  47414. // We're mainly based on the logic defined into the FreeCamera code
  47415. var TouchCamera = (function (_super) {
  47416. __extends(TouchCamera, _super);
  47417. //-- end properties for backward compatibility for inputs
  47418. function TouchCamera(name, position, scene) {
  47419. var _this = _super.call(this, name, position, scene) || this;
  47420. _this.inputs.addTouch();
  47421. _this._setupInputs();
  47422. return _this;
  47423. }
  47424. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  47425. //-- Begin properties for backward compatibility for inputs
  47426. get: function () {
  47427. var touch = this.inputs.attached["touch"];
  47428. if (touch)
  47429. return touch.touchAngularSensibility;
  47430. },
  47431. set: function (value) {
  47432. var touch = this.inputs.attached["touch"];
  47433. if (touch)
  47434. touch.touchAngularSensibility = value;
  47435. },
  47436. enumerable: true,
  47437. configurable: true
  47438. });
  47439. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  47440. get: function () {
  47441. var touch = this.inputs.attached["touch"];
  47442. if (touch)
  47443. return touch.touchMoveSensibility;
  47444. },
  47445. set: function (value) {
  47446. var touch = this.inputs.attached["touch"];
  47447. if (touch)
  47448. touch.touchMoveSensibility = value;
  47449. },
  47450. enumerable: true,
  47451. configurable: true
  47452. });
  47453. TouchCamera.prototype.getClassName = function () {
  47454. return "TouchCamera";
  47455. };
  47456. TouchCamera.prototype._setupInputs = function () {
  47457. var mouse = this.inputs.attached["mouse"];
  47458. if (mouse) {
  47459. mouse.touchEnabled = false;
  47460. }
  47461. };
  47462. return TouchCamera;
  47463. }(BABYLON.FreeCamera));
  47464. BABYLON.TouchCamera = TouchCamera;
  47465. })(BABYLON || (BABYLON = {}));
  47466. //# sourceMappingURL=babylon.touchCamera.js.map
  47467. var BABYLON;
  47468. (function (BABYLON) {
  47469. var ProceduralTexture = (function (_super) {
  47470. __extends(ProceduralTexture, _super);
  47471. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  47472. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47473. if (isCube === void 0) { isCube = false; }
  47474. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  47475. _this.isCube = isCube;
  47476. _this.isEnabled = true;
  47477. _this._currentRefreshId = -1;
  47478. _this._refreshRate = 1;
  47479. _this._vertexBuffers = {};
  47480. _this._uniforms = new Array();
  47481. _this._samplers = new Array();
  47482. _this._textures = new Array();
  47483. _this._floats = new Array();
  47484. _this._floatsArrays = {};
  47485. _this._colors3 = new Array();
  47486. _this._colors4 = new Array();
  47487. _this._vectors2 = new Array();
  47488. _this._vectors3 = new Array();
  47489. _this._matrices = new Array();
  47490. _this._fallbackTextureUsed = false;
  47491. scene._proceduralTextures.push(_this);
  47492. _this.name = name;
  47493. _this.isRenderTarget = true;
  47494. _this._size = size;
  47495. _this._generateMipMaps = generateMipMaps;
  47496. _this.setFragment(fragment);
  47497. _this._fallbackTexture = fallbackTexture;
  47498. var engine = scene.getEngine();
  47499. if (isCube) {
  47500. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  47501. _this.setFloat("face", 0);
  47502. }
  47503. else {
  47504. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  47505. }
  47506. // VBO
  47507. var vertices = [];
  47508. vertices.push(1, 1);
  47509. vertices.push(-1, 1);
  47510. vertices.push(-1, -1);
  47511. vertices.push(1, -1);
  47512. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  47513. // Indices
  47514. var indices = [];
  47515. indices.push(0);
  47516. indices.push(1);
  47517. indices.push(2);
  47518. indices.push(0);
  47519. indices.push(2);
  47520. indices.push(3);
  47521. _this._indexBuffer = engine.createIndexBuffer(indices);
  47522. return _this;
  47523. }
  47524. ProceduralTexture.prototype.reset = function () {
  47525. if (this._effect === undefined) {
  47526. return;
  47527. }
  47528. var engine = this.getScene().getEngine();
  47529. engine._releaseEffect(this._effect);
  47530. };
  47531. ProceduralTexture.prototype.isReady = function () {
  47532. var _this = this;
  47533. var engine = this.getScene().getEngine();
  47534. var shaders;
  47535. if (!this._fragment) {
  47536. return false;
  47537. }
  47538. if (this._fallbackTextureUsed) {
  47539. return true;
  47540. }
  47541. if (this._fragment.fragmentElement !== undefined) {
  47542. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  47543. }
  47544. else {
  47545. shaders = { vertex: "procedural", fragment: this._fragment };
  47546. }
  47547. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  47548. _this.releaseInternalTexture();
  47549. if (_this._fallbackTexture) {
  47550. _this._texture = _this._fallbackTexture._texture;
  47551. _this._texture.references++;
  47552. }
  47553. _this._fallbackTextureUsed = true;
  47554. });
  47555. return this._effect.isReady();
  47556. };
  47557. ProceduralTexture.prototype.resetRefreshCounter = function () {
  47558. this._currentRefreshId = -1;
  47559. };
  47560. ProceduralTexture.prototype.setFragment = function (fragment) {
  47561. this._fragment = fragment;
  47562. };
  47563. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  47564. get: function () {
  47565. return this._refreshRate;
  47566. },
  47567. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  47568. set: function (value) {
  47569. this._refreshRate = value;
  47570. this.resetRefreshCounter();
  47571. },
  47572. enumerable: true,
  47573. configurable: true
  47574. });
  47575. ProceduralTexture.prototype._shouldRender = function () {
  47576. if (!this.isEnabled || !this.isReady() || !this._texture) {
  47577. return false;
  47578. }
  47579. if (this._fallbackTextureUsed) {
  47580. return false;
  47581. }
  47582. if (this._currentRefreshId === -1) {
  47583. this._currentRefreshId = 1;
  47584. return true;
  47585. }
  47586. if (this.refreshRate === this._currentRefreshId) {
  47587. this._currentRefreshId = 1;
  47588. return true;
  47589. }
  47590. this._currentRefreshId++;
  47591. return false;
  47592. };
  47593. ProceduralTexture.prototype.getRenderSize = function () {
  47594. return this._size;
  47595. };
  47596. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  47597. if (this._fallbackTextureUsed) {
  47598. return;
  47599. }
  47600. this.releaseInternalTexture();
  47601. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  47602. };
  47603. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  47604. if (this._uniforms.indexOf(uniformName) === -1) {
  47605. this._uniforms.push(uniformName);
  47606. }
  47607. };
  47608. ProceduralTexture.prototype.setTexture = function (name, texture) {
  47609. if (this._samplers.indexOf(name) === -1) {
  47610. this._samplers.push(name);
  47611. }
  47612. this._textures[name] = texture;
  47613. return this;
  47614. };
  47615. ProceduralTexture.prototype.setFloat = function (name, value) {
  47616. this._checkUniform(name);
  47617. this._floats[name] = value;
  47618. return this;
  47619. };
  47620. ProceduralTexture.prototype.setFloats = function (name, value) {
  47621. this._checkUniform(name);
  47622. this._floatsArrays[name] = value;
  47623. return this;
  47624. };
  47625. ProceduralTexture.prototype.setColor3 = function (name, value) {
  47626. this._checkUniform(name);
  47627. this._colors3[name] = value;
  47628. return this;
  47629. };
  47630. ProceduralTexture.prototype.setColor4 = function (name, value) {
  47631. this._checkUniform(name);
  47632. this._colors4[name] = value;
  47633. return this;
  47634. };
  47635. ProceduralTexture.prototype.setVector2 = function (name, value) {
  47636. this._checkUniform(name);
  47637. this._vectors2[name] = value;
  47638. return this;
  47639. };
  47640. ProceduralTexture.prototype.setVector3 = function (name, value) {
  47641. this._checkUniform(name);
  47642. this._vectors3[name] = value;
  47643. return this;
  47644. };
  47645. ProceduralTexture.prototype.setMatrix = function (name, value) {
  47646. this._checkUniform(name);
  47647. this._matrices[name] = value;
  47648. return this;
  47649. };
  47650. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  47651. var scene = this.getScene();
  47652. var engine = scene.getEngine();
  47653. // Render
  47654. engine.enableEffect(this._effect);
  47655. engine.setState(false);
  47656. // Texture
  47657. for (var name in this._textures) {
  47658. this._effect.setTexture(name, this._textures[name]);
  47659. }
  47660. // Float
  47661. for (name in this._floats) {
  47662. this._effect.setFloat(name, this._floats[name]);
  47663. }
  47664. // Floats
  47665. for (name in this._floatsArrays) {
  47666. this._effect.setArray(name, this._floatsArrays[name]);
  47667. }
  47668. // Color3
  47669. for (name in this._colors3) {
  47670. this._effect.setColor3(name, this._colors3[name]);
  47671. }
  47672. // Color4
  47673. for (name in this._colors4) {
  47674. var color = this._colors4[name];
  47675. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47676. }
  47677. // Vector2
  47678. for (name in this._vectors2) {
  47679. this._effect.setVector2(name, this._vectors2[name]);
  47680. }
  47681. // Vector3
  47682. for (name in this._vectors3) {
  47683. this._effect.setVector3(name, this._vectors3[name]);
  47684. }
  47685. // Matrix
  47686. for (name in this._matrices) {
  47687. this._effect.setMatrix(name, this._matrices[name]);
  47688. }
  47689. if (this.isCube) {
  47690. for (var face = 0; face < 6; face++) {
  47691. engine.bindFramebuffer(this._texture, face);
  47692. // VBOs
  47693. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  47694. this._effect.setFloat("face", face);
  47695. // Clear
  47696. engine.clear(scene.clearColor, true, true, true);
  47697. // Draw order
  47698. engine.draw(true, 0, 6);
  47699. // Mipmaps
  47700. if (face === 5) {
  47701. engine.generateMipMapsForCubemap(this._texture);
  47702. }
  47703. }
  47704. }
  47705. else {
  47706. engine.bindFramebuffer(this._texture);
  47707. // VBOs
  47708. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  47709. // Clear
  47710. engine.clear(scene.clearColor, true, true, true);
  47711. // Draw order
  47712. engine.draw(true, 0, 6);
  47713. }
  47714. // Unbind
  47715. engine.unBindFramebuffer(this._texture, this.isCube);
  47716. if (this.onGenerated) {
  47717. this.onGenerated();
  47718. }
  47719. };
  47720. ProceduralTexture.prototype.clone = function () {
  47721. var textureSize = this.getSize();
  47722. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  47723. // Base texture
  47724. newTexture.hasAlpha = this.hasAlpha;
  47725. newTexture.level = this.level;
  47726. // RenderTarget Texture
  47727. newTexture.coordinatesMode = this.coordinatesMode;
  47728. return newTexture;
  47729. };
  47730. ProceduralTexture.prototype.dispose = function () {
  47731. var index = this.getScene()._proceduralTextures.indexOf(this);
  47732. if (index >= 0) {
  47733. this.getScene()._proceduralTextures.splice(index, 1);
  47734. }
  47735. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  47736. if (vertexBuffer) {
  47737. vertexBuffer.dispose();
  47738. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  47739. }
  47740. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  47741. this._indexBuffer = null;
  47742. }
  47743. _super.prototype.dispose.call(this);
  47744. };
  47745. return ProceduralTexture;
  47746. }(BABYLON.Texture));
  47747. BABYLON.ProceduralTexture = ProceduralTexture;
  47748. })(BABYLON || (BABYLON = {}));
  47749. //# sourceMappingURL=babylon.proceduralTexture.js.map
  47750. /// <reference path="babylon.proceduralTexture.ts" />
  47751. var BABYLON;
  47752. (function (BABYLON) {
  47753. var CustomProceduralTexture = (function (_super) {
  47754. __extends(CustomProceduralTexture, _super);
  47755. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  47756. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  47757. _this._animate = true;
  47758. _this._time = 0;
  47759. _this._texturePath = texturePath;
  47760. //Try to load json
  47761. _this.loadJson(texturePath);
  47762. _this.refreshRate = 1;
  47763. return _this;
  47764. }
  47765. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  47766. var _this = this;
  47767. var that = this;
  47768. function noConfigFile() {
  47769. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  47770. try {
  47771. that.setFragment(that._texturePath);
  47772. }
  47773. catch (ex) {
  47774. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  47775. }
  47776. }
  47777. var configFileUrl = jsonUrl + "/config.json";
  47778. var xhr = new XMLHttpRequest();
  47779. xhr.open("GET", configFileUrl, true);
  47780. xhr.addEventListener("load", function () {
  47781. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  47782. try {
  47783. _this._config = JSON.parse(xhr.response);
  47784. _this.updateShaderUniforms();
  47785. _this.updateTextures();
  47786. _this.setFragment(_this._texturePath + "/custom");
  47787. _this._animate = _this._config.animate;
  47788. _this.refreshRate = _this._config.refreshrate;
  47789. }
  47790. catch (ex) {
  47791. noConfigFile();
  47792. }
  47793. }
  47794. else {
  47795. noConfigFile();
  47796. }
  47797. }, false);
  47798. xhr.addEventListener("error", function () {
  47799. noConfigFile();
  47800. }, false);
  47801. try {
  47802. xhr.send();
  47803. }
  47804. catch (ex) {
  47805. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  47806. }
  47807. };
  47808. CustomProceduralTexture.prototype.isReady = function () {
  47809. if (!_super.prototype.isReady.call(this)) {
  47810. return false;
  47811. }
  47812. for (var name in this._textures) {
  47813. var texture = this._textures[name];
  47814. if (!texture.isReady()) {
  47815. return false;
  47816. }
  47817. }
  47818. return true;
  47819. };
  47820. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  47821. if (this._animate) {
  47822. this._time += this.getScene().getAnimationRatio() * 0.03;
  47823. this.updateShaderUniforms();
  47824. }
  47825. _super.prototype.render.call(this, useCameraPostProcess);
  47826. };
  47827. CustomProceduralTexture.prototype.updateTextures = function () {
  47828. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  47829. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  47830. }
  47831. };
  47832. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  47833. if (this._config) {
  47834. for (var j = 0; j < this._config.uniforms.length; j++) {
  47835. var uniform = this._config.uniforms[j];
  47836. switch (uniform.type) {
  47837. case "float":
  47838. this.setFloat(uniform.name, uniform.value);
  47839. break;
  47840. case "color3":
  47841. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  47842. break;
  47843. case "color4":
  47844. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  47845. break;
  47846. case "vector2":
  47847. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  47848. break;
  47849. case "vector3":
  47850. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  47851. break;
  47852. }
  47853. }
  47854. }
  47855. this.setFloat("time", this._time);
  47856. };
  47857. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  47858. get: function () {
  47859. return this._animate;
  47860. },
  47861. set: function (value) {
  47862. this._animate = value;
  47863. },
  47864. enumerable: true,
  47865. configurable: true
  47866. });
  47867. return CustomProceduralTexture;
  47868. }(BABYLON.ProceduralTexture));
  47869. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  47870. })(BABYLON || (BABYLON = {}));
  47871. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  47872. var BABYLON;
  47873. (function (BABYLON) {
  47874. var FreeCameraGamepadInput = (function () {
  47875. function FreeCameraGamepadInput() {
  47876. this.gamepadAngularSensibility = 200;
  47877. this.gamepadMoveSensibility = 40;
  47878. // private members
  47879. this._cameraTransform = BABYLON.Matrix.Identity();
  47880. this._deltaTransform = BABYLON.Vector3.Zero();
  47881. this._vector3 = BABYLON.Vector3.Zero();
  47882. this._vector2 = BABYLON.Vector2.Zero();
  47883. }
  47884. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  47885. var _this = this;
  47886. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  47887. };
  47888. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  47889. if (this._gamepads) {
  47890. this._gamepads.dispose();
  47891. }
  47892. this.gamepad = null;
  47893. };
  47894. FreeCameraGamepadInput.prototype.checkInputs = function () {
  47895. if (this.gamepad && this.gamepad.leftStick) {
  47896. var camera = this.camera;
  47897. var LSValues = this.gamepad.leftStick;
  47898. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  47899. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  47900. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  47901. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  47902. var RSValues = this.gamepad.rightStick;
  47903. if (RSValues) {
  47904. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  47905. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  47906. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  47907. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  47908. }
  47909. else {
  47910. RSValues = { x: 0, y: 0 };
  47911. }
  47912. if (!camera.rotationQuaternion) {
  47913. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  47914. }
  47915. else {
  47916. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  47917. }
  47918. var speed = camera._computeLocalCameraSpeed() * 50.0;
  47919. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  47920. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  47921. camera.cameraDirection.addInPlace(this._deltaTransform);
  47922. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  47923. camera.cameraRotation.addInPlace(this._vector2);
  47924. }
  47925. };
  47926. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  47927. // Only the first gamepad found can control the camera
  47928. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  47929. // prioritize XBOX gamepads.
  47930. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  47931. this.gamepad = gamepad;
  47932. }
  47933. }
  47934. };
  47935. FreeCameraGamepadInput.prototype.getTypeName = function () {
  47936. return "FreeCameraGamepadInput";
  47937. };
  47938. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  47939. return "gamepad";
  47940. };
  47941. return FreeCameraGamepadInput;
  47942. }());
  47943. __decorate([
  47944. BABYLON.serialize()
  47945. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  47946. __decorate([
  47947. BABYLON.serialize()
  47948. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  47949. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  47950. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  47951. })(BABYLON || (BABYLON = {}));
  47952. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  47953. var BABYLON;
  47954. (function (BABYLON) {
  47955. var ArcRotateCameraGamepadInput = (function () {
  47956. function ArcRotateCameraGamepadInput() {
  47957. this.gamepadRotationSensibility = 80;
  47958. this.gamepadMoveSensibility = 40;
  47959. }
  47960. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  47961. var _this = this;
  47962. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  47963. };
  47964. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  47965. if (this._gamepads) {
  47966. this._gamepads.dispose();
  47967. }
  47968. this.gamepad = null;
  47969. };
  47970. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  47971. if (this.gamepad) {
  47972. var camera = this.camera;
  47973. var RSValues = this.gamepad.rightStick;
  47974. if (RSValues) {
  47975. if (RSValues.x != 0) {
  47976. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  47977. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  47978. camera.inertialAlphaOffset += normalizedRX;
  47979. }
  47980. }
  47981. if (RSValues.y != 0) {
  47982. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  47983. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  47984. camera.inertialBetaOffset += normalizedRY;
  47985. }
  47986. }
  47987. }
  47988. var LSValues = this.gamepad.leftStick;
  47989. if (LSValues && LSValues.y != 0) {
  47990. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  47991. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  47992. this.camera.inertialRadiusOffset -= normalizedLY;
  47993. }
  47994. }
  47995. }
  47996. };
  47997. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  47998. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  47999. // prioritize XBOX gamepads.
  48000. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  48001. this.gamepad = gamepad;
  48002. }
  48003. }
  48004. };
  48005. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  48006. return "ArcRotateCameraGamepadInput";
  48007. };
  48008. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  48009. return "gamepad";
  48010. };
  48011. return ArcRotateCameraGamepadInput;
  48012. }());
  48013. __decorate([
  48014. BABYLON.serialize()
  48015. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  48016. __decorate([
  48017. BABYLON.serialize()
  48018. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  48019. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  48020. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  48021. })(BABYLON || (BABYLON = {}));
  48022. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  48023. var BABYLON;
  48024. (function (BABYLON) {
  48025. var Gamepads = (function () {
  48026. function Gamepads(ongamedpadconnected, ongamedpaddisconnected) {
  48027. var _this = this;
  48028. this.babylonGamepads = [];
  48029. this.oneGamepadConnected = false;
  48030. this.isMonitoring = false;
  48031. this.gamepadEventSupported = 'GamepadEvent' in window;
  48032. this.gamepadSupport = (navigator.getGamepads ||
  48033. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  48034. this._callbackGamepadConnected = ongamedpadconnected;
  48035. this._callbackGamepadDisconnected = ongamedpaddisconnected;
  48036. if (this.gamepadSupport) {
  48037. //first add already-connected gamepads
  48038. this._updateGamepadObjects();
  48039. if (this.babylonGamepads.length) {
  48040. this._startMonitoringGamepads();
  48041. }
  48042. // Checking if the gamepad connected event is supported (like in Firefox)
  48043. if (this.gamepadEventSupported) {
  48044. this._onGamepadConnectedEvent = function (evt) {
  48045. _this._onGamepadConnected(evt.gamepad);
  48046. };
  48047. this._onGamepadDisonnectedEvent = function (evt) {
  48048. _this._onGamepadDisconnected(evt.gamepad);
  48049. };
  48050. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  48051. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  48052. }
  48053. else {
  48054. this._startMonitoringGamepads();
  48055. }
  48056. }
  48057. }
  48058. Gamepads.prototype.dispose = function () {
  48059. if (this._onGamepadConnectedEvent) {
  48060. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  48061. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  48062. this._onGamepadConnectedEvent = null;
  48063. this._onGamepadDisonnectedEvent = null;
  48064. }
  48065. this.oneGamepadConnected = false;
  48066. this._stopMonitoringGamepads();
  48067. this.babylonGamepads = [];
  48068. };
  48069. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  48070. // Protection code for Chrome which has a very buggy gamepad implementation...
  48071. // And raises a connected event on disconnection for instance
  48072. if (gamepad.index in this.babylonGamepads) {
  48073. return;
  48074. }
  48075. var newGamepad = this._addNewGamepad(gamepad);
  48076. if (this._callbackGamepadConnected)
  48077. this._callbackGamepadConnected(newGamepad);
  48078. this._startMonitoringGamepads();
  48079. };
  48080. Gamepads.prototype._addNewGamepad = function (gamepad) {
  48081. if (!this.oneGamepadConnected) {
  48082. this.oneGamepadConnected = true;
  48083. }
  48084. var newGamepad;
  48085. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  48086. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  48087. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  48088. }
  48089. else if (gamepad.pose) {
  48090. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  48091. }
  48092. else {
  48093. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  48094. }
  48095. this.babylonGamepads.push(newGamepad);
  48096. return newGamepad;
  48097. };
  48098. Gamepads.prototype._onGamepadDisconnected = function (gamepad) {
  48099. // Remove the gamepad from the list of gamepads to monitor.
  48100. for (var i in this.babylonGamepads) {
  48101. if (this.babylonGamepads[i].index == gamepad.index) {
  48102. this.babylonGamepads.splice(+i, 1);
  48103. break;
  48104. }
  48105. }
  48106. // If no gamepads are left, stop the polling loop.
  48107. if (this.babylonGamepads.length == 0) {
  48108. this._stopMonitoringGamepads();
  48109. this.oneGamepadConnected = false;
  48110. }
  48111. if (this._callbackGamepadDisconnected)
  48112. this._callbackGamepadDisconnected(gamepad);
  48113. };
  48114. Gamepads.prototype._startMonitoringGamepads = function () {
  48115. if (!this.isMonitoring) {
  48116. this.isMonitoring = true;
  48117. this._checkGamepadsStatus();
  48118. }
  48119. };
  48120. Gamepads.prototype._stopMonitoringGamepads = function () {
  48121. this.isMonitoring = false;
  48122. };
  48123. Gamepads.prototype._checkGamepadsStatus = function () {
  48124. var _this = this;
  48125. // Hack to be compatible Chrome
  48126. this._updateGamepadObjects();
  48127. for (var i in this.babylonGamepads) {
  48128. this.babylonGamepads[i].update();
  48129. }
  48130. if (this.isMonitoring) {
  48131. if (window.requestAnimationFrame) {
  48132. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  48133. }
  48134. else if (window.mozRequestAnimationFrame) {
  48135. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  48136. }
  48137. else if (window.webkitRequestAnimationFrame) {
  48138. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  48139. }
  48140. }
  48141. };
  48142. // This function is called only on Chrome, which does not properly support
  48143. // connection/disconnection events and forces you to recopy again the gamepad object
  48144. Gamepads.prototype._updateGamepadObjects = function () {
  48145. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  48146. for (var i = 0; i < gamepads.length; i++) {
  48147. if (gamepads[i]) {
  48148. if (!(gamepads[i].index in this.babylonGamepads)) {
  48149. var newGamepad = this._addNewGamepad(gamepads[i]);
  48150. if (this._callbackGamepadConnected) {
  48151. this._callbackGamepadConnected(newGamepad);
  48152. }
  48153. }
  48154. else {
  48155. // Forced to copy again this object for Chrome for unknown reason
  48156. this.babylonGamepads[i].browserGamepad = gamepads[i];
  48157. }
  48158. }
  48159. }
  48160. };
  48161. return Gamepads;
  48162. }());
  48163. BABYLON.Gamepads = Gamepads;
  48164. var StickValues = (function () {
  48165. function StickValues(x, y) {
  48166. this.x = x;
  48167. this.y = y;
  48168. }
  48169. return StickValues;
  48170. }());
  48171. BABYLON.StickValues = StickValues;
  48172. var Gamepad = (function () {
  48173. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  48174. if (leftStickX === void 0) { leftStickX = 0; }
  48175. if (leftStickY === void 0) { leftStickY = 1; }
  48176. if (rightStickX === void 0) { rightStickX = 2; }
  48177. if (rightStickY === void 0) { rightStickY = 3; }
  48178. this.id = id;
  48179. this.index = index;
  48180. this.browserGamepad = browserGamepad;
  48181. this.type = Gamepad.GAMEPAD;
  48182. this._leftStickAxisX = leftStickX;
  48183. this._leftStickAxisY = leftStickY;
  48184. this._rightStickAxisX = rightStickX;
  48185. this._rightStickAxisY = rightStickY;
  48186. if (this.browserGamepad.axes.length >= 2) {
  48187. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  48188. }
  48189. if (this.browserGamepad.axes.length >= 4) {
  48190. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  48191. }
  48192. }
  48193. Gamepad.prototype.onleftstickchanged = function (callback) {
  48194. this._onleftstickchanged = callback;
  48195. };
  48196. Gamepad.prototype.onrightstickchanged = function (callback) {
  48197. this._onrightstickchanged = callback;
  48198. };
  48199. Object.defineProperty(Gamepad.prototype, "leftStick", {
  48200. get: function () {
  48201. return this._leftStick;
  48202. },
  48203. set: function (newValues) {
  48204. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  48205. this._onleftstickchanged(newValues);
  48206. }
  48207. this._leftStick = newValues;
  48208. },
  48209. enumerable: true,
  48210. configurable: true
  48211. });
  48212. Object.defineProperty(Gamepad.prototype, "rightStick", {
  48213. get: function () {
  48214. return this._rightStick;
  48215. },
  48216. set: function (newValues) {
  48217. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  48218. this._onrightstickchanged(newValues);
  48219. }
  48220. this._rightStick = newValues;
  48221. },
  48222. enumerable: true,
  48223. configurable: true
  48224. });
  48225. Gamepad.prototype.update = function () {
  48226. if (this._leftStick) {
  48227. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  48228. }
  48229. if (this._rightStick) {
  48230. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  48231. }
  48232. };
  48233. return Gamepad;
  48234. }());
  48235. Gamepad.GAMEPAD = 0;
  48236. Gamepad.GENERIC = 1;
  48237. Gamepad.XBOX = 2;
  48238. Gamepad.POSE_ENABLED = 3;
  48239. BABYLON.Gamepad = Gamepad;
  48240. var GenericPad = (function (_super) {
  48241. __extends(GenericPad, _super);
  48242. function GenericPad(id, index, browserGamepad) {
  48243. var _this = _super.call(this, id, index, browserGamepad) || this;
  48244. _this.type = Gamepad.GENERIC;
  48245. _this._buttons = new Array(browserGamepad.buttons.length);
  48246. return _this;
  48247. }
  48248. GenericPad.prototype.onbuttondown = function (callback) {
  48249. this._onbuttondown = callback;
  48250. };
  48251. GenericPad.prototype.onbuttonup = function (callback) {
  48252. this._onbuttonup = callback;
  48253. };
  48254. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  48255. if (newValue !== currentValue) {
  48256. if (this._onbuttondown && newValue === 1) {
  48257. this._onbuttondown(buttonIndex);
  48258. }
  48259. if (this._onbuttonup && newValue === 0) {
  48260. this._onbuttonup(buttonIndex);
  48261. }
  48262. }
  48263. return newValue;
  48264. };
  48265. GenericPad.prototype.update = function () {
  48266. _super.prototype.update.call(this);
  48267. for (var index = 0; index < this._buttons.length; index++) {
  48268. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  48269. }
  48270. };
  48271. return GenericPad;
  48272. }(Gamepad));
  48273. BABYLON.GenericPad = GenericPad;
  48274. var Xbox360Button;
  48275. (function (Xbox360Button) {
  48276. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  48277. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  48278. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  48279. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  48280. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  48281. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  48282. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  48283. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  48284. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  48285. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  48286. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  48287. var Xbox360Dpad;
  48288. (function (Xbox360Dpad) {
  48289. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  48290. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  48291. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  48292. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  48293. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  48294. var Xbox360Pad = (function (_super) {
  48295. __extends(Xbox360Pad, _super);
  48296. function Xbox360Pad(id, index, gamepad, xboxOne) {
  48297. if (xboxOne === void 0) { xboxOne = false; }
  48298. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  48299. _this._leftTrigger = 0;
  48300. _this._rightTrigger = 0;
  48301. _this._buttonA = 0;
  48302. _this._buttonB = 0;
  48303. _this._buttonX = 0;
  48304. _this._buttonY = 0;
  48305. _this._buttonBack = 0;
  48306. _this._buttonStart = 0;
  48307. _this._buttonLB = 0;
  48308. _this._buttonRB = 0;
  48309. _this._buttonLeftStick = 0;
  48310. _this._buttonRightStick = 0;
  48311. _this._dPadUp = 0;
  48312. _this._dPadDown = 0;
  48313. _this._dPadLeft = 0;
  48314. _this._dPadRight = 0;
  48315. _this._isXboxOnePad = false;
  48316. _this.type = Gamepad.XBOX;
  48317. _this._isXboxOnePad = xboxOne;
  48318. return _this;
  48319. }
  48320. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  48321. this._onlefttriggerchanged = callback;
  48322. };
  48323. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  48324. this._onrighttriggerchanged = callback;
  48325. };
  48326. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  48327. get: function () {
  48328. return this._leftTrigger;
  48329. },
  48330. set: function (newValue) {
  48331. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  48332. this._onlefttriggerchanged(newValue);
  48333. }
  48334. this._leftTrigger = newValue;
  48335. },
  48336. enumerable: true,
  48337. configurable: true
  48338. });
  48339. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  48340. get: function () {
  48341. return this._rightTrigger;
  48342. },
  48343. set: function (newValue) {
  48344. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  48345. this._onrighttriggerchanged(newValue);
  48346. }
  48347. this._rightTrigger = newValue;
  48348. },
  48349. enumerable: true,
  48350. configurable: true
  48351. });
  48352. Xbox360Pad.prototype.onbuttondown = function (callback) {
  48353. this._onbuttondown = callback;
  48354. };
  48355. Xbox360Pad.prototype.onbuttonup = function (callback) {
  48356. this._onbuttonup = callback;
  48357. };
  48358. Xbox360Pad.prototype.ondpaddown = function (callback) {
  48359. this._ondpaddown = callback;
  48360. };
  48361. Xbox360Pad.prototype.ondpadup = function (callback) {
  48362. this._ondpadup = callback;
  48363. };
  48364. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  48365. if (newValue !== currentValue) {
  48366. if (this._onbuttondown && newValue === 1) {
  48367. this._onbuttondown(buttonType);
  48368. }
  48369. if (this._onbuttonup && newValue === 0) {
  48370. this._onbuttonup(buttonType);
  48371. }
  48372. }
  48373. return newValue;
  48374. };
  48375. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  48376. if (newValue !== currentValue) {
  48377. if (this._ondpaddown && newValue === 1) {
  48378. this._ondpaddown(buttonType);
  48379. }
  48380. if (this._ondpadup && newValue === 0) {
  48381. this._ondpadup(buttonType);
  48382. }
  48383. }
  48384. return newValue;
  48385. };
  48386. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  48387. get: function () {
  48388. return this._buttonA;
  48389. },
  48390. set: function (value) {
  48391. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  48392. },
  48393. enumerable: true,
  48394. configurable: true
  48395. });
  48396. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  48397. get: function () {
  48398. return this._buttonB;
  48399. },
  48400. set: function (value) {
  48401. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  48402. },
  48403. enumerable: true,
  48404. configurable: true
  48405. });
  48406. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  48407. get: function () {
  48408. return this._buttonX;
  48409. },
  48410. set: function (value) {
  48411. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  48412. },
  48413. enumerable: true,
  48414. configurable: true
  48415. });
  48416. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  48417. get: function () {
  48418. return this._buttonY;
  48419. },
  48420. set: function (value) {
  48421. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  48422. },
  48423. enumerable: true,
  48424. configurable: true
  48425. });
  48426. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  48427. get: function () {
  48428. return this._buttonStart;
  48429. },
  48430. set: function (value) {
  48431. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  48432. },
  48433. enumerable: true,
  48434. configurable: true
  48435. });
  48436. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  48437. get: function () {
  48438. return this._buttonBack;
  48439. },
  48440. set: function (value) {
  48441. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  48442. },
  48443. enumerable: true,
  48444. configurable: true
  48445. });
  48446. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  48447. get: function () {
  48448. return this._buttonLB;
  48449. },
  48450. set: function (value) {
  48451. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  48452. },
  48453. enumerable: true,
  48454. configurable: true
  48455. });
  48456. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  48457. get: function () {
  48458. return this._buttonRB;
  48459. },
  48460. set: function (value) {
  48461. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  48462. },
  48463. enumerable: true,
  48464. configurable: true
  48465. });
  48466. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  48467. get: function () {
  48468. return this._buttonLeftStick;
  48469. },
  48470. set: function (value) {
  48471. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  48472. },
  48473. enumerable: true,
  48474. configurable: true
  48475. });
  48476. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  48477. get: function () {
  48478. return this._buttonRightStick;
  48479. },
  48480. set: function (value) {
  48481. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  48482. },
  48483. enumerable: true,
  48484. configurable: true
  48485. });
  48486. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  48487. get: function () {
  48488. return this._dPadUp;
  48489. },
  48490. set: function (value) {
  48491. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  48492. },
  48493. enumerable: true,
  48494. configurable: true
  48495. });
  48496. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  48497. get: function () {
  48498. return this._dPadDown;
  48499. },
  48500. set: function (value) {
  48501. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  48502. },
  48503. enumerable: true,
  48504. configurable: true
  48505. });
  48506. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  48507. get: function () {
  48508. return this._dPadLeft;
  48509. },
  48510. set: function (value) {
  48511. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  48512. },
  48513. enumerable: true,
  48514. configurable: true
  48515. });
  48516. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  48517. get: function () {
  48518. return this._dPadRight;
  48519. },
  48520. set: function (value) {
  48521. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  48522. },
  48523. enumerable: true,
  48524. configurable: true
  48525. });
  48526. Xbox360Pad.prototype.update = function () {
  48527. _super.prototype.update.call(this);
  48528. if (this._isXboxOnePad) {
  48529. this.buttonA = this.browserGamepad.buttons[0].value;
  48530. this.buttonB = this.browserGamepad.buttons[1].value;
  48531. this.buttonX = this.browserGamepad.buttons[2].value;
  48532. this.buttonY = this.browserGamepad.buttons[3].value;
  48533. this.buttonLB = this.browserGamepad.buttons[4].value;
  48534. this.buttonRB = this.browserGamepad.buttons[5].value;
  48535. this.leftTrigger = this.browserGamepad.axes[2];
  48536. this.rightTrigger = this.browserGamepad.axes[5];
  48537. this.buttonBack = this.browserGamepad.buttons[9].value;
  48538. this.buttonStart = this.browserGamepad.buttons[8].value;
  48539. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  48540. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  48541. this.dPadUp = this.browserGamepad.buttons[11].value;
  48542. this.dPadDown = this.browserGamepad.buttons[12].value;
  48543. this.dPadLeft = this.browserGamepad.buttons[13].value;
  48544. this.dPadRight = this.browserGamepad.buttons[14].value;
  48545. }
  48546. else {
  48547. this.buttonA = this.browserGamepad.buttons[0].value;
  48548. this.buttonB = this.browserGamepad.buttons[1].value;
  48549. this.buttonX = this.browserGamepad.buttons[2].value;
  48550. this.buttonY = this.browserGamepad.buttons[3].value;
  48551. this.buttonLB = this.browserGamepad.buttons[4].value;
  48552. this.buttonRB = this.browserGamepad.buttons[5].value;
  48553. this.leftTrigger = this.browserGamepad.buttons[6].value;
  48554. this.rightTrigger = this.browserGamepad.buttons[7].value;
  48555. this.buttonBack = this.browserGamepad.buttons[8].value;
  48556. this.buttonStart = this.browserGamepad.buttons[9].value;
  48557. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  48558. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  48559. this.dPadUp = this.browserGamepad.buttons[12].value;
  48560. this.dPadDown = this.browserGamepad.buttons[13].value;
  48561. this.dPadLeft = this.browserGamepad.buttons[14].value;
  48562. this.dPadRight = this.browserGamepad.buttons[15].value;
  48563. }
  48564. };
  48565. return Xbox360Pad;
  48566. }(Gamepad));
  48567. BABYLON.Xbox360Pad = Xbox360Pad;
  48568. })(BABYLON || (BABYLON = {}));
  48569. //# sourceMappingURL=babylon.gamepads.js.map
  48570. var BABYLON;
  48571. (function (BABYLON) {
  48572. var PoseEnabledControllerType;
  48573. (function (PoseEnabledControllerType) {
  48574. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  48575. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  48576. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  48577. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  48578. var PoseEnabledControllerHelper = (function () {
  48579. function PoseEnabledControllerHelper() {
  48580. }
  48581. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  48582. // for now, only Oculus and Vive are supported
  48583. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  48584. return new OculusTouchController(vrGamepad);
  48585. }
  48586. else {
  48587. return new ViveController(vrGamepad);
  48588. }
  48589. };
  48590. return PoseEnabledControllerHelper;
  48591. }());
  48592. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  48593. var PoseEnabledController = (function (_super) {
  48594. __extends(PoseEnabledController, _super);
  48595. function PoseEnabledController(vrGamepad) {
  48596. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  48597. _this.vrGamepad = vrGamepad;
  48598. _this.deviceScaleFactor = 1;
  48599. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  48600. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  48601. _this.controllerType = PoseEnabledControllerType.GENERIC;
  48602. _this.position = BABYLON.Vector3.Zero();
  48603. _this.rotationQuaternion = new BABYLON.Quaternion();
  48604. _this.devicePosition = BABYLON.Vector3.Zero();
  48605. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  48606. _this._calculatedPosition = BABYLON.Vector3.Zero();
  48607. _this._calculatedRotation = new BABYLON.Quaternion();
  48608. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  48609. return _this;
  48610. }
  48611. PoseEnabledController.prototype.update = function () {
  48612. _super.prototype.update.call(this);
  48613. var pose = this.vrGamepad.pose;
  48614. this.updateFromDevice(pose);
  48615. if (this._mesh) {
  48616. this._mesh.position.copyFrom(this._calculatedPosition);
  48617. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  48618. }
  48619. };
  48620. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  48621. if (poseData) {
  48622. this.rawPose = poseData;
  48623. if (poseData.position) {
  48624. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  48625. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  48626. this.devicePosition.z *= -1;
  48627. }
  48628. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  48629. this._calculatedPosition.addInPlace(this.position);
  48630. }
  48631. if (poseData.orientation) {
  48632. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  48633. if (this._mesh) {
  48634. if (this._mesh.getScene().useRightHandedSystem) {
  48635. this.deviceRotationQuaternion.z *= -1;
  48636. this.deviceRotationQuaternion.w *= -1;
  48637. }
  48638. else {
  48639. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  48640. }
  48641. }
  48642. // if the camera is set, rotate to the camera's rotation
  48643. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  48644. }
  48645. }
  48646. };
  48647. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  48648. if (this._mesh) {
  48649. this._mesh.parent = undefined;
  48650. }
  48651. this._mesh = mesh;
  48652. if (this._poseControlledCamera) {
  48653. this._mesh.parent = this._poseControlledCamera;
  48654. }
  48655. if (!this._mesh.rotationQuaternion) {
  48656. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  48657. }
  48658. };
  48659. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  48660. this._poseControlledCamera = camera;
  48661. if (this._mesh) {
  48662. this._mesh.parent = this._poseControlledCamera;
  48663. }
  48664. };
  48665. PoseEnabledController.prototype.detachMesh = function () {
  48666. this._mesh = undefined;
  48667. };
  48668. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  48669. get: function () {
  48670. return this._mesh;
  48671. },
  48672. enumerable: true,
  48673. configurable: true
  48674. });
  48675. PoseEnabledController.prototype.getForwardRay = function (length) {
  48676. if (length === void 0) { length = 100; }
  48677. if (!this.mesh) {
  48678. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  48679. }
  48680. var m = this.mesh.getWorldMatrix();
  48681. var origin = m.getTranslation();
  48682. var forward = new BABYLON.Vector3(0, 0, -1);
  48683. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  48684. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  48685. return new BABYLON.Ray(origin, direction, length);
  48686. };
  48687. return PoseEnabledController;
  48688. }(BABYLON.Gamepad));
  48689. BABYLON.PoseEnabledController = PoseEnabledController;
  48690. var WebVRController = (function (_super) {
  48691. __extends(WebVRController, _super);
  48692. function WebVRController(vrGamepad) {
  48693. var _this = _super.call(this, vrGamepad) || this;
  48694. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  48695. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  48696. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  48697. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  48698. _this.onPadStateChangedObservable = new BABYLON.Observable();
  48699. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  48700. _this.pad = { x: 0, y: 0 };
  48701. // avoid GC, store state in a tmp object
  48702. _this._changes = {
  48703. pressChanged: false,
  48704. touchChanged: false,
  48705. valueChanged: false,
  48706. changed: false
  48707. };
  48708. _this._buttons = new Array(vrGamepad.buttons.length);
  48709. _this.hand = vrGamepad.hand;
  48710. return _this;
  48711. }
  48712. WebVRController.prototype.onButtonStateChange = function (callback) {
  48713. this._onButtonStateChange = callback;
  48714. };
  48715. WebVRController.prototype.update = function () {
  48716. _super.prototype.update.call(this);
  48717. for (var index = 0; index < this._buttons.length; index++) {
  48718. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  48719. }
  48720. ;
  48721. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  48722. this.pad.x = this.leftStick.x;
  48723. this.pad.y = this.leftStick.y;
  48724. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  48725. }
  48726. };
  48727. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  48728. if (!currentState) {
  48729. this._buttons[buttonIndex] = {
  48730. pressed: newState.pressed,
  48731. touched: newState.touched,
  48732. value: newState.value
  48733. };
  48734. return;
  48735. }
  48736. this._checkChanges(newState, currentState);
  48737. if (this._changes.changed) {
  48738. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  48739. this.handleButtonChange(buttonIndex, newState, this._changes);
  48740. }
  48741. this._buttons[buttonIndex].pressed = newState.pressed;
  48742. this._buttons[buttonIndex].touched = newState.touched;
  48743. // oculus triggers are never 0, thou not touched.
  48744. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  48745. };
  48746. WebVRController.prototype._checkChanges = function (newState, currentState) {
  48747. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  48748. this._changes.touchChanged = newState.touched !== currentState.touched;
  48749. this._changes.valueChanged = newState.value !== currentState.value;
  48750. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  48751. return this._changes;
  48752. };
  48753. return WebVRController;
  48754. }(PoseEnabledController));
  48755. BABYLON.WebVRController = WebVRController;
  48756. var OculusTouchController = (function (_super) {
  48757. __extends(OculusTouchController, _super);
  48758. function OculusTouchController(vrGamepad) {
  48759. var _this = _super.call(this, vrGamepad) || this;
  48760. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  48761. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  48762. _this.controllerType = PoseEnabledControllerType.OCULUS;
  48763. return _this;
  48764. }
  48765. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  48766. var _this = this;
  48767. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  48768. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  48769. /*
  48770. Parent Mesh name: oculus_touch_left
  48771. - body
  48772. - trigger
  48773. - thumbstick
  48774. - grip
  48775. - button_y
  48776. - button_x
  48777. - button_enter
  48778. */
  48779. _this._defaultModel = newMeshes[1];
  48780. if (meshLoaded) {
  48781. meshLoaded(_this._defaultModel);
  48782. }
  48783. _this.attachToMesh(_this._defaultModel);
  48784. });
  48785. };
  48786. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  48787. // helper getters for left and right hand.
  48788. get: function () {
  48789. if (this.hand === 'right') {
  48790. return this.onMainButtonStateChangedObservable;
  48791. }
  48792. else {
  48793. throw new Error('No A button on left hand');
  48794. }
  48795. },
  48796. enumerable: true,
  48797. configurable: true
  48798. });
  48799. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  48800. get: function () {
  48801. if (this.hand === 'right') {
  48802. return this.onSecondaryButtonStateChangedObservable;
  48803. }
  48804. else {
  48805. throw new Error('No B button on left hand');
  48806. }
  48807. },
  48808. enumerable: true,
  48809. configurable: true
  48810. });
  48811. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  48812. get: function () {
  48813. if (this.hand === 'left') {
  48814. return this.onMainButtonStateChangedObservable;
  48815. }
  48816. else {
  48817. throw new Error('No X button on right hand');
  48818. }
  48819. },
  48820. enumerable: true,
  48821. configurable: true
  48822. });
  48823. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  48824. get: function () {
  48825. if (this.hand === 'left') {
  48826. return this.onSecondaryButtonStateChangedObservable;
  48827. }
  48828. else {
  48829. throw new Error('No Y button on right hand');
  48830. }
  48831. },
  48832. enumerable: true,
  48833. configurable: true
  48834. });
  48835. /*
  48836. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  48837. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  48838. 2) secondary trigger (same)
  48839. 3) A (right) X (left), touch, pressed = value
  48840. 4) B / Y
  48841. 5) thumb rest
  48842. */
  48843. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  48844. var notifyObject = state; //{ state: state, changes: changes };
  48845. var triggerDirection = this.hand === 'right' ? -1 : 1;
  48846. switch (buttonIdx) {
  48847. case 0:
  48848. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  48849. return;
  48850. case 1:
  48851. if (this._defaultModel) {
  48852. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  48853. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  48854. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  48855. }
  48856. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  48857. return;
  48858. case 2:
  48859. if (this._defaultModel) {
  48860. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  48861. }
  48862. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  48863. return;
  48864. case 3:
  48865. if (this._defaultModel) {
  48866. if (notifyObject.pressed) {
  48867. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  48868. }
  48869. else {
  48870. (this._defaultModel.getChildren()[1]).position.y = 0;
  48871. }
  48872. }
  48873. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  48874. return;
  48875. case 4:
  48876. if (this._defaultModel) {
  48877. if (notifyObject.pressed) {
  48878. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  48879. }
  48880. else {
  48881. (this._defaultModel.getChildren()[2]).position.y = 0;
  48882. }
  48883. }
  48884. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  48885. return;
  48886. case 5:
  48887. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  48888. return;
  48889. }
  48890. };
  48891. return OculusTouchController;
  48892. }(WebVRController));
  48893. BABYLON.OculusTouchController = OculusTouchController;
  48894. var ViveController = (function (_super) {
  48895. __extends(ViveController, _super);
  48896. function ViveController(vrGamepad) {
  48897. var _this = _super.call(this, vrGamepad) || this;
  48898. _this.controllerType = PoseEnabledControllerType.VIVE;
  48899. return _this;
  48900. }
  48901. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  48902. var _this = this;
  48903. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  48904. /*
  48905. Parent Mesh name: ViveWand
  48906. - body
  48907. - r_gripper
  48908. - l_gripper
  48909. - menu_button
  48910. - system_button
  48911. - trackpad
  48912. - trigger
  48913. - LED
  48914. */
  48915. _this._defaultModel = newMeshes[1];
  48916. if (meshLoaded) {
  48917. meshLoaded(_this._defaultModel);
  48918. }
  48919. _this.attachToMesh(_this._defaultModel);
  48920. });
  48921. };
  48922. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  48923. get: function () {
  48924. return this.onMainButtonStateChangedObservable;
  48925. },
  48926. enumerable: true,
  48927. configurable: true
  48928. });
  48929. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  48930. get: function () {
  48931. return this.onMainButtonStateChangedObservable;
  48932. },
  48933. enumerable: true,
  48934. configurable: true
  48935. });
  48936. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  48937. get: function () {
  48938. return this.onSecondaryButtonStateChangedObservable;
  48939. },
  48940. enumerable: true,
  48941. configurable: true
  48942. });
  48943. /**
  48944. * Vive mapping:
  48945. * 0: touchpad
  48946. * 1: trigger
  48947. * 2: left AND right buttons
  48948. * 3: menu button
  48949. */
  48950. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  48951. var notifyObject = state; //{ state: state, changes: changes };
  48952. switch (buttonIdx) {
  48953. case 0:
  48954. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  48955. return;
  48956. case 1:
  48957. if (this._defaultModel) {
  48958. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  48959. }
  48960. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  48961. return;
  48962. case 2:
  48963. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  48964. return;
  48965. case 3:
  48966. if (this._defaultModel) {
  48967. if (notifyObject.pressed) {
  48968. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  48969. }
  48970. else {
  48971. (this._defaultModel.getChildren()[2]).position.y = 0;
  48972. }
  48973. }
  48974. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  48975. return;
  48976. }
  48977. };
  48978. return ViveController;
  48979. }(WebVRController));
  48980. BABYLON.ViveController = ViveController;
  48981. })(BABYLON || (BABYLON = {}));
  48982. //# sourceMappingURL=babylon.extendedGamepad.js.map
  48983. /// <reference path="babylon.targetCamera.ts" />
  48984. var BABYLON;
  48985. (function (BABYLON) {
  48986. var FollowCamera = (function (_super) {
  48987. __extends(FollowCamera, _super);
  48988. function FollowCamera(name, position, scene, lockedTarget) {
  48989. var _this = _super.call(this, name, position, scene) || this;
  48990. _this.radius = 12;
  48991. _this.rotationOffset = 0;
  48992. _this.heightOffset = 4;
  48993. _this.cameraAcceleration = 0.05;
  48994. _this.maxCameraSpeed = 20;
  48995. _this.lockedTarget = lockedTarget;
  48996. return _this;
  48997. }
  48998. FollowCamera.prototype.getRadians = function (degrees) {
  48999. return degrees * Math.PI / 180;
  49000. };
  49001. FollowCamera.prototype.follow = function (cameraTarget) {
  49002. if (!cameraTarget)
  49003. return;
  49004. var yRotation;
  49005. if (cameraTarget.rotationQuaternion) {
  49006. var rotMatrix = new BABYLON.Matrix();
  49007. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  49008. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  49009. }
  49010. else {
  49011. yRotation = cameraTarget.rotation.y;
  49012. }
  49013. var radians = this.getRadians(this.rotationOffset) + yRotation;
  49014. var targetPosition = cameraTarget.getAbsolutePosition();
  49015. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  49016. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  49017. var dx = targetX - this.position.x;
  49018. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  49019. var dz = (targetZ) - this.position.z;
  49020. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  49021. var vy = dy * this.cameraAcceleration;
  49022. var vz = dz * this.cameraAcceleration * 2;
  49023. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  49024. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  49025. }
  49026. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  49027. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  49028. }
  49029. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  49030. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  49031. }
  49032. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  49033. this.setTarget(targetPosition);
  49034. };
  49035. FollowCamera.prototype._checkInputs = function () {
  49036. _super.prototype._checkInputs.call(this);
  49037. this.follow(this.lockedTarget);
  49038. };
  49039. FollowCamera.prototype.getClassName = function () {
  49040. return "FollowCamera";
  49041. };
  49042. return FollowCamera;
  49043. }(BABYLON.TargetCamera));
  49044. __decorate([
  49045. BABYLON.serialize()
  49046. ], FollowCamera.prototype, "radius", void 0);
  49047. __decorate([
  49048. BABYLON.serialize()
  49049. ], FollowCamera.prototype, "rotationOffset", void 0);
  49050. __decorate([
  49051. BABYLON.serialize()
  49052. ], FollowCamera.prototype, "heightOffset", void 0);
  49053. __decorate([
  49054. BABYLON.serialize()
  49055. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  49056. __decorate([
  49057. BABYLON.serialize()
  49058. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  49059. __decorate([
  49060. BABYLON.serializeAsMeshReference("lockedTargetId")
  49061. ], FollowCamera.prototype, "lockedTarget", void 0);
  49062. BABYLON.FollowCamera = FollowCamera;
  49063. var ArcFollowCamera = (function (_super) {
  49064. __extends(ArcFollowCamera, _super);
  49065. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  49066. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  49067. _this.alpha = alpha;
  49068. _this.beta = beta;
  49069. _this.radius = radius;
  49070. _this.target = target;
  49071. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  49072. _this.follow();
  49073. return _this;
  49074. }
  49075. ArcFollowCamera.prototype.follow = function () {
  49076. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  49077. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  49078. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  49079. var targetPosition = this.target.getAbsolutePosition();
  49080. this.position = targetPosition.add(this._cartesianCoordinates);
  49081. this.setTarget(targetPosition);
  49082. };
  49083. ArcFollowCamera.prototype._checkInputs = function () {
  49084. _super.prototype._checkInputs.call(this);
  49085. this.follow();
  49086. };
  49087. ArcFollowCamera.prototype.getClassName = function () {
  49088. return "ArcFollowCamera";
  49089. };
  49090. return ArcFollowCamera;
  49091. }(BABYLON.TargetCamera));
  49092. BABYLON.ArcFollowCamera = ArcFollowCamera;
  49093. })(BABYLON || (BABYLON = {}));
  49094. //# sourceMappingURL=babylon.followCamera.js.map
  49095. /// <reference path="babylon.touchCamera.ts" />
  49096. var BABYLON;
  49097. (function (BABYLON) {
  49098. // We're mainly based on the logic defined into the FreeCamera code
  49099. var UniversalCamera = (function (_super) {
  49100. __extends(UniversalCamera, _super);
  49101. //-- end properties for backward compatibility for inputs
  49102. function UniversalCamera(name, position, scene) {
  49103. var _this = _super.call(this, name, position, scene) || this;
  49104. _this.inputs.addGamepad();
  49105. return _this;
  49106. }
  49107. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  49108. //-- Begin properties for backward compatibility for inputs
  49109. get: function () {
  49110. var gamepad = this.inputs.attached["gamepad"];
  49111. if (gamepad)
  49112. return gamepad.gamepadAngularSensibility;
  49113. },
  49114. set: function (value) {
  49115. var gamepad = this.inputs.attached["gamepad"];
  49116. if (gamepad)
  49117. gamepad.gamepadAngularSensibility = value;
  49118. },
  49119. enumerable: true,
  49120. configurable: true
  49121. });
  49122. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  49123. get: function () {
  49124. var gamepad = this.inputs.attached["gamepad"];
  49125. if (gamepad)
  49126. return gamepad.gamepadMoveSensibility;
  49127. },
  49128. set: function (value) {
  49129. var gamepad = this.inputs.attached["gamepad"];
  49130. if (gamepad)
  49131. gamepad.gamepadMoveSensibility = value;
  49132. },
  49133. enumerable: true,
  49134. configurable: true
  49135. });
  49136. UniversalCamera.prototype.getClassName = function () {
  49137. return "UniversalCamera";
  49138. };
  49139. return UniversalCamera;
  49140. }(BABYLON.TouchCamera));
  49141. BABYLON.UniversalCamera = UniversalCamera;
  49142. })(BABYLON || (BABYLON = {}));
  49143. //# sourceMappingURL=babylon.universalCamera.js.map
  49144. /// <reference path="babylon.universalCamera.ts" />
  49145. var BABYLON;
  49146. (function (BABYLON) {
  49147. // We're mainly based on the logic defined into the FreeCamera code
  49148. var GamepadCamera = (function (_super) {
  49149. __extends(GamepadCamera, _super);
  49150. //-- end properties for backward compatibility for inputs
  49151. function GamepadCamera(name, position, scene) {
  49152. return _super.call(this, name, position, scene) || this;
  49153. }
  49154. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  49155. //-- Begin properties for backward compatibility for inputs
  49156. get: function () {
  49157. var gamepad = this.inputs.attached["gamepad"];
  49158. if (gamepad)
  49159. return gamepad.gamepadAngularSensibility;
  49160. },
  49161. set: function (value) {
  49162. var gamepad = this.inputs.attached["gamepad"];
  49163. if (gamepad)
  49164. gamepad.gamepadAngularSensibility = value;
  49165. },
  49166. enumerable: true,
  49167. configurable: true
  49168. });
  49169. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  49170. get: function () {
  49171. var gamepad = this.inputs.attached["gamepad"];
  49172. if (gamepad)
  49173. return gamepad.gamepadMoveSensibility;
  49174. },
  49175. set: function (value) {
  49176. var gamepad = this.inputs.attached["gamepad"];
  49177. if (gamepad)
  49178. gamepad.gamepadMoveSensibility = value;
  49179. },
  49180. enumerable: true,
  49181. configurable: true
  49182. });
  49183. GamepadCamera.prototype.getClassName = function () {
  49184. return "GamepadCamera";
  49185. };
  49186. return GamepadCamera;
  49187. }(BABYLON.UniversalCamera));
  49188. BABYLON.GamepadCamera = GamepadCamera;
  49189. })(BABYLON || (BABYLON = {}));
  49190. //# sourceMappingURL=babylon.gamepadCamera.js.map
  49191. var BABYLON;
  49192. (function (BABYLON) {
  49193. var PostProcessRenderPipelineManager = (function () {
  49194. function PostProcessRenderPipelineManager() {
  49195. this._renderPipelines = {};
  49196. }
  49197. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  49198. this._renderPipelines[renderPipeline._name] = renderPipeline;
  49199. };
  49200. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  49201. var renderPipeline = this._renderPipelines[renderPipelineName];
  49202. if (!renderPipeline) {
  49203. return;
  49204. }
  49205. renderPipeline._attachCameras(cameras, unique);
  49206. };
  49207. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  49208. var renderPipeline = this._renderPipelines[renderPipelineName];
  49209. if (!renderPipeline) {
  49210. return;
  49211. }
  49212. renderPipeline._detachCameras(cameras);
  49213. };
  49214. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  49215. var renderPipeline = this._renderPipelines[renderPipelineName];
  49216. if (!renderPipeline) {
  49217. return;
  49218. }
  49219. renderPipeline._enableEffect(renderEffectName, cameras);
  49220. };
  49221. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  49222. var renderPipeline = this._renderPipelines[renderPipelineName];
  49223. if (!renderPipeline) {
  49224. return;
  49225. }
  49226. renderPipeline._disableEffect(renderEffectName, cameras);
  49227. };
  49228. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  49229. var renderPipeline = this._renderPipelines[renderPipelineName];
  49230. if (!renderPipeline) {
  49231. return;
  49232. }
  49233. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  49234. };
  49235. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  49236. var renderPipeline = this._renderPipelines[renderPipelineName];
  49237. if (!renderPipeline) {
  49238. return;
  49239. }
  49240. renderPipeline._disableDisplayOnlyPass(cameras);
  49241. };
  49242. PostProcessRenderPipelineManager.prototype.update = function () {
  49243. for (var renderPipelineName in this._renderPipelines) {
  49244. var pipeline = this._renderPipelines[renderPipelineName];
  49245. if (!pipeline.isSupported) {
  49246. pipeline.dispose();
  49247. delete this._renderPipelines[renderPipelineName];
  49248. }
  49249. else {
  49250. pipeline._update();
  49251. }
  49252. }
  49253. };
  49254. return PostProcessRenderPipelineManager;
  49255. }());
  49256. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  49257. })(BABYLON || (BABYLON = {}));
  49258. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  49259. var BABYLON;
  49260. (function (BABYLON) {
  49261. var PostProcessRenderPass = (function () {
  49262. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  49263. this._enabled = true;
  49264. this._refCount = 0;
  49265. this._name = name;
  49266. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  49267. this.setRenderList(renderList);
  49268. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  49269. this._renderTexture.onAfterRenderObservable.add(afterRender);
  49270. this._scene = scene;
  49271. this._renderList = renderList;
  49272. }
  49273. // private
  49274. PostProcessRenderPass.prototype._incRefCount = function () {
  49275. if (this._refCount === 0) {
  49276. this._scene.customRenderTargets.push(this._renderTexture);
  49277. }
  49278. return ++this._refCount;
  49279. };
  49280. PostProcessRenderPass.prototype._decRefCount = function () {
  49281. this._refCount--;
  49282. if (this._refCount <= 0) {
  49283. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  49284. }
  49285. return this._refCount;
  49286. };
  49287. PostProcessRenderPass.prototype._update = function () {
  49288. this.setRenderList(this._renderList);
  49289. };
  49290. // public
  49291. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  49292. this._renderTexture.renderList = renderList;
  49293. };
  49294. PostProcessRenderPass.prototype.getRenderTexture = function () {
  49295. return this._renderTexture;
  49296. };
  49297. return PostProcessRenderPass;
  49298. }());
  49299. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  49300. })(BABYLON || (BABYLON = {}));
  49301. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  49302. var BABYLON;
  49303. (function (BABYLON) {
  49304. var PostProcessRenderEffect = (function () {
  49305. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  49306. this._engine = engine;
  49307. this._name = name;
  49308. this._singleInstance = singleInstance || true;
  49309. this._getPostProcess = getPostProcess;
  49310. this._cameras = [];
  49311. this._indicesForCamera = [];
  49312. this._postProcesses = {};
  49313. this._renderPasses = {};
  49314. this._renderEffectAsPasses = {};
  49315. }
  49316. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  49317. get: function () {
  49318. for (var index in this._postProcesses) {
  49319. if (!this._postProcesses[index].isSupported) {
  49320. return false;
  49321. }
  49322. }
  49323. return true;
  49324. },
  49325. enumerable: true,
  49326. configurable: true
  49327. });
  49328. PostProcessRenderEffect.prototype._update = function () {
  49329. for (var renderPassName in this._renderPasses) {
  49330. this._renderPasses[renderPassName]._update();
  49331. }
  49332. };
  49333. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  49334. this._renderPasses[renderPass._name] = renderPass;
  49335. this._linkParameters();
  49336. };
  49337. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  49338. delete this._renderPasses[renderPass._name];
  49339. this._linkParameters();
  49340. };
  49341. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  49342. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  49343. this._linkParameters();
  49344. };
  49345. PostProcessRenderEffect.prototype.getPass = function (passName) {
  49346. for (var renderPassName in this._renderPasses) {
  49347. if (renderPassName === passName) {
  49348. return this._renderPasses[passName];
  49349. }
  49350. }
  49351. };
  49352. PostProcessRenderEffect.prototype.emptyPasses = function () {
  49353. this._renderPasses = {};
  49354. this._linkParameters();
  49355. };
  49356. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  49357. var cameraKey;
  49358. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49359. for (var i = 0; i < _cam.length; i++) {
  49360. var camera = _cam[i];
  49361. var cameraName = camera.name;
  49362. if (this._singleInstance) {
  49363. cameraKey = 0;
  49364. }
  49365. else {
  49366. cameraKey = cameraName;
  49367. }
  49368. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  49369. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  49370. if (!this._indicesForCamera[cameraName]) {
  49371. this._indicesForCamera[cameraName] = [];
  49372. }
  49373. this._indicesForCamera[cameraName].push(index);
  49374. if (this._cameras.indexOf(camera) === -1) {
  49375. this._cameras[cameraName] = camera;
  49376. }
  49377. for (var passName in this._renderPasses) {
  49378. this._renderPasses[passName]._incRefCount();
  49379. }
  49380. }
  49381. this._linkParameters();
  49382. };
  49383. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  49384. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49385. for (var i = 0; i < _cam.length; i++) {
  49386. var camera = _cam[i];
  49387. var cameraName = camera.name;
  49388. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  49389. var index = this._cameras.indexOf(cameraName);
  49390. this._indicesForCamera.splice(index, 1);
  49391. this._cameras.splice(index, 1);
  49392. for (var passName in this._renderPasses) {
  49393. this._renderPasses[passName]._decRefCount();
  49394. }
  49395. }
  49396. };
  49397. PostProcessRenderEffect.prototype._enable = function (cameras) {
  49398. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49399. for (var i = 0; i < _cam.length; i++) {
  49400. var camera = _cam[i];
  49401. var cameraName = camera.name;
  49402. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  49403. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  49404. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  49405. }
  49406. }
  49407. for (var passName in this._renderPasses) {
  49408. this._renderPasses[passName]._incRefCount();
  49409. }
  49410. }
  49411. };
  49412. PostProcessRenderEffect.prototype._disable = function (cameras) {
  49413. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49414. for (var i = 0; i < _cam.length; i++) {
  49415. var camera = _cam[i];
  49416. var cameraName = camera.Name;
  49417. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  49418. for (var passName in this._renderPasses) {
  49419. this._renderPasses[passName]._decRefCount();
  49420. }
  49421. }
  49422. };
  49423. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  49424. if (this._singleInstance) {
  49425. return this._postProcesses[0];
  49426. }
  49427. else {
  49428. return this._postProcesses[camera.name];
  49429. }
  49430. };
  49431. PostProcessRenderEffect.prototype._linkParameters = function () {
  49432. var _this = this;
  49433. for (var index in this._postProcesses) {
  49434. if (this.applyParameters) {
  49435. this.applyParameters(this._postProcesses[index]);
  49436. }
  49437. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  49438. _this._linkTextures(effect);
  49439. });
  49440. }
  49441. };
  49442. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  49443. for (var renderPassName in this._renderPasses) {
  49444. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  49445. }
  49446. for (var renderEffectName in this._renderEffectAsPasses) {
  49447. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  49448. }
  49449. };
  49450. return PostProcessRenderEffect;
  49451. }());
  49452. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  49453. })(BABYLON || (BABYLON = {}));
  49454. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  49455. var BABYLON;
  49456. (function (BABYLON) {
  49457. var PostProcessRenderPipeline = (function () {
  49458. function PostProcessRenderPipeline(engine, name) {
  49459. this._engine = engine;
  49460. this._name = name;
  49461. this._renderEffects = new Array();
  49462. this._renderEffectsForIsolatedPass = new Array();
  49463. this._cameras = [];
  49464. }
  49465. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  49466. get: function () {
  49467. for (var renderEffectName in this._renderEffects) {
  49468. if (!this._renderEffects[renderEffectName].isSupported) {
  49469. return false;
  49470. }
  49471. }
  49472. return true;
  49473. },
  49474. enumerable: true,
  49475. configurable: true
  49476. });
  49477. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  49478. this._renderEffects[renderEffect._name] = renderEffect;
  49479. };
  49480. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  49481. var renderEffects = this._renderEffects[renderEffectName];
  49482. if (!renderEffects) {
  49483. return;
  49484. }
  49485. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  49486. };
  49487. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  49488. var renderEffects = this._renderEffects[renderEffectName];
  49489. if (!renderEffects) {
  49490. return;
  49491. }
  49492. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  49493. };
  49494. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  49495. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49496. var indicesToDelete = [];
  49497. var i;
  49498. for (i = 0; i < _cam.length; i++) {
  49499. var camera = _cam[i];
  49500. var cameraName = camera.name;
  49501. if (this._cameras.indexOf(camera) === -1) {
  49502. this._cameras[cameraName] = camera;
  49503. }
  49504. else if (unique) {
  49505. indicesToDelete.push(i);
  49506. }
  49507. }
  49508. for (i = 0; i < indicesToDelete.length; i++) {
  49509. cameras.splice(indicesToDelete[i], 1);
  49510. }
  49511. for (var renderEffectName in this._renderEffects) {
  49512. this._renderEffects[renderEffectName]._attachCameras(_cam);
  49513. }
  49514. };
  49515. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  49516. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49517. for (var renderEffectName in this._renderEffects) {
  49518. this._renderEffects[renderEffectName]._detachCameras(_cam);
  49519. }
  49520. for (var i = 0; i < _cam.length; i++) {
  49521. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  49522. }
  49523. };
  49524. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  49525. var _this = this;
  49526. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49527. var pass = null;
  49528. var renderEffectName;
  49529. for (renderEffectName in this._renderEffects) {
  49530. pass = this._renderEffects[renderEffectName].getPass(passName);
  49531. if (pass != null) {
  49532. break;
  49533. }
  49534. }
  49535. if (pass === null) {
  49536. return;
  49537. }
  49538. for (renderEffectName in this._renderEffects) {
  49539. this._renderEffects[renderEffectName]._disable(_cam);
  49540. }
  49541. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  49542. for (var i = 0; i < _cam.length; i++) {
  49543. var camera = _cam[i];
  49544. var cameraName = camera.name;
  49545. 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); });
  49546. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  49547. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  49548. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  49549. }
  49550. };
  49551. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  49552. var _this = this;
  49553. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  49554. for (var i = 0; i < _cam.length; i++) {
  49555. var camera = _cam[i];
  49556. var cameraName = camera.name;
  49557. 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); });
  49558. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  49559. }
  49560. for (var renderEffectName in this._renderEffects) {
  49561. this._renderEffects[renderEffectName]._enable(_cam);
  49562. }
  49563. };
  49564. PostProcessRenderPipeline.prototype._update = function () {
  49565. for (var renderEffectName in this._renderEffects) {
  49566. this._renderEffects[renderEffectName]._update();
  49567. }
  49568. for (var i = 0; i < this._cameras.length; i++) {
  49569. var cameraName = this._cameras[i].name;
  49570. if (this._renderEffectsForIsolatedPass[cameraName]) {
  49571. this._renderEffectsForIsolatedPass[cameraName]._update();
  49572. }
  49573. }
  49574. };
  49575. PostProcessRenderPipeline.prototype._reset = function () {
  49576. this._renderEffects = new Array();
  49577. this._renderEffectsForIsolatedPass = new Array();
  49578. };
  49579. PostProcessRenderPipeline.prototype.dispose = function () {
  49580. // Must be implemented by children
  49581. };
  49582. return PostProcessRenderPipeline;
  49583. }());
  49584. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  49585. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  49586. __decorate([
  49587. BABYLON.serialize()
  49588. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  49589. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  49590. })(BABYLON || (BABYLON = {}));
  49591. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  49592. var BABYLON;
  49593. (function (BABYLON) {
  49594. var DepthRenderer = (function () {
  49595. function DepthRenderer(scene, type) {
  49596. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  49597. var _this = this;
  49598. this._viewMatrix = BABYLON.Matrix.Zero();
  49599. this._projectionMatrix = BABYLON.Matrix.Zero();
  49600. this._transformMatrix = BABYLON.Matrix.Zero();
  49601. this._worldViewProjection = BABYLON.Matrix.Zero();
  49602. this._scene = scene;
  49603. var engine = scene.getEngine();
  49604. // Render target
  49605. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  49606. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49607. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49608. this._depthMap.refreshRate = 1;
  49609. this._depthMap.renderParticles = false;
  49610. this._depthMap.renderList = null;
  49611. // set default depth value to 1.0 (far away)
  49612. this._depthMap.onClearObservable.add(function (engine) {
  49613. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  49614. });
  49615. // Custom render function
  49616. var renderSubMesh = function (subMesh) {
  49617. var mesh = subMesh.getRenderingMesh();
  49618. var scene = _this._scene;
  49619. var engine = scene.getEngine();
  49620. // Culling
  49621. engine.setState(subMesh.getMaterial().backFaceCulling);
  49622. // Managing instances
  49623. var batch = mesh._getInstancesRenderList(subMesh._id);
  49624. if (batch.mustReturn) {
  49625. return;
  49626. }
  49627. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  49628. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  49629. engine.enableEffect(_this._effect);
  49630. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  49631. var material = subMesh.getMaterial();
  49632. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  49633. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  49634. // Alpha test
  49635. if (material && material.needAlphaTesting()) {
  49636. var alphaTexture = material.getAlphaTestTexture();
  49637. _this._effect.setTexture("diffuseSampler", alphaTexture);
  49638. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  49639. }
  49640. // Bones
  49641. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49642. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49643. }
  49644. // Draw
  49645. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  49646. }
  49647. };
  49648. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  49649. var index;
  49650. for (index = 0; index < opaqueSubMeshes.length; index++) {
  49651. renderSubMesh(opaqueSubMeshes.data[index]);
  49652. }
  49653. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  49654. renderSubMesh(alphaTestSubMeshes.data[index]);
  49655. }
  49656. };
  49657. }
  49658. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  49659. var material = subMesh.getMaterial();
  49660. if (material.disableDepthWrite) {
  49661. return false;
  49662. }
  49663. var defines = [];
  49664. var attribs = [BABYLON.VertexBuffer.PositionKind];
  49665. var mesh = subMesh.getMesh();
  49666. var scene = mesh.getScene();
  49667. // Alpha test
  49668. if (material && material.needAlphaTesting()) {
  49669. defines.push("#define ALPHATEST");
  49670. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49671. attribs.push(BABYLON.VertexBuffer.UVKind);
  49672. defines.push("#define UV1");
  49673. }
  49674. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  49675. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  49676. defines.push("#define UV2");
  49677. }
  49678. }
  49679. // Bones
  49680. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49681. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49682. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49683. if (mesh.numBoneInfluencers > 4) {
  49684. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49685. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49686. }
  49687. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49688. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49689. }
  49690. else {
  49691. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49692. }
  49693. // Instances
  49694. if (useInstances) {
  49695. defines.push("#define INSTANCES");
  49696. attribs.push("world0");
  49697. attribs.push("world1");
  49698. attribs.push("world2");
  49699. attribs.push("world3");
  49700. }
  49701. // Get correct effect
  49702. var join = defines.join("\n");
  49703. if (this._cachedDefines !== join) {
  49704. this._cachedDefines = join;
  49705. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  49706. }
  49707. return this._effect.isReady();
  49708. };
  49709. DepthRenderer.prototype.getDepthMap = function () {
  49710. return this._depthMap;
  49711. };
  49712. // Methods
  49713. DepthRenderer.prototype.dispose = function () {
  49714. this._depthMap.dispose();
  49715. };
  49716. return DepthRenderer;
  49717. }());
  49718. BABYLON.DepthRenderer = DepthRenderer;
  49719. })(BABYLON || (BABYLON = {}));
  49720. //# sourceMappingURL=babylon.depthRenderer.js.map
  49721. var BABYLON;
  49722. (function (BABYLON) {
  49723. var SSAORenderingPipeline = (function (_super) {
  49724. __extends(SSAORenderingPipeline, _super);
  49725. /**
  49726. * @constructor
  49727. * @param {string} name - The rendering pipeline name
  49728. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49729. * @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 }
  49730. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49731. */
  49732. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  49733. var _this = _super.call(this, scene.getEngine(), name) || this;
  49734. // Members
  49735. /**
  49736. * The PassPostProcess id in the pipeline that contains the original scene color
  49737. * @type {string}
  49738. */
  49739. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  49740. /**
  49741. * The SSAO PostProcess id in the pipeline
  49742. * @type {string}
  49743. */
  49744. _this.SSAORenderEffect = "SSAORenderEffect";
  49745. /**
  49746. * The horizontal blur PostProcess id in the pipeline
  49747. * @type {string}
  49748. */
  49749. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  49750. /**
  49751. * The vertical blur PostProcess id in the pipeline
  49752. * @type {string}
  49753. */
  49754. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  49755. /**
  49756. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  49757. * @type {string}
  49758. */
  49759. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  49760. /**
  49761. * The output strength of the SSAO post-process. Default value is 1.0.
  49762. * @type {number}
  49763. */
  49764. _this.totalStrength = 1.0;
  49765. /**
  49766. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  49767. * @type {number}
  49768. */
  49769. _this.radius = 0.0001;
  49770. /**
  49771. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  49772. * Must not be equal to fallOff and superior to fallOff.
  49773. * Default value is 0.975
  49774. * @type {number}
  49775. */
  49776. _this.area = 0.0075;
  49777. /**
  49778. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  49779. * Must not be equal to area and inferior to area.
  49780. * Default value is 0.0
  49781. * @type {number}
  49782. */
  49783. _this.fallOff = 0.000001;
  49784. /**
  49785. * The base color of the SSAO post-process
  49786. * The final result is "base + ssao" between [0, 1]
  49787. * @type {number}
  49788. */
  49789. _this.base = 0.5;
  49790. _this._firstUpdate = true;
  49791. _this._scene = scene;
  49792. // Set up assets
  49793. _this._createRandomTexture();
  49794. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  49795. var ssaoRatio = ratio.ssaoRatio || ratio;
  49796. var combineRatio = ratio.combineRatio || ratio;
  49797. _this._ratio = {
  49798. ssaoRatio: ssaoRatio,
  49799. combineRatio: combineRatio
  49800. };
  49801. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  49802. _this._createSSAOPostProcess(ssaoRatio);
  49803. _this._createBlurPostProcess(ssaoRatio);
  49804. _this._createSSAOCombinePostProcess(combineRatio);
  49805. // Set up pipeline
  49806. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  49807. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  49808. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  49809. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  49810. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  49811. // Finish
  49812. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49813. if (cameras)
  49814. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49815. return _this;
  49816. }
  49817. // Public Methods
  49818. /**
  49819. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  49820. */
  49821. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  49822. if (disableDepthRender === void 0) { disableDepthRender = false; }
  49823. for (var i = 0; i < this._scene.cameras.length; i++) {
  49824. var camera = this._scene.cameras[i];
  49825. this._originalColorPostProcess.dispose(camera);
  49826. this._ssaoPostProcess.dispose(camera);
  49827. this._blurHPostProcess.dispose(camera);
  49828. this._blurVPostProcess.dispose(camera);
  49829. this._ssaoCombinePostProcess.dispose(camera);
  49830. }
  49831. this._randomTexture.dispose();
  49832. if (disableDepthRender)
  49833. this._scene.disableDepthRenderer();
  49834. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49835. _super.prototype.dispose.call(this);
  49836. };
  49837. // Private Methods
  49838. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  49839. var _this = this;
  49840. /*
  49841. var samplerOffsets = [
  49842. -8.0, -6.0, -4.0, -2.0,
  49843. 0.0,
  49844. 2.0, 4.0, 6.0, 8.0
  49845. ];
  49846. */
  49847. var samples = 16;
  49848. var samplerOffsets = [];
  49849. for (var i = -8; i < 8; i++) {
  49850. samplerOffsets.push(i * 2);
  49851. }
  49852. 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");
  49853. this._blurHPostProcess.onApply = function (effect) {
  49854. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  49855. effect.setTexture("depthSampler", _this._depthTexture);
  49856. if (_this._firstUpdate) {
  49857. effect.setArray("samplerOffsets", samplerOffsets);
  49858. }
  49859. };
  49860. 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");
  49861. this._blurVPostProcess.onApply = function (effect) {
  49862. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  49863. effect.setTexture("depthSampler", _this._depthTexture);
  49864. if (_this._firstUpdate) {
  49865. effect.setArray("samplerOffsets", samplerOffsets);
  49866. _this._firstUpdate = false;
  49867. }
  49868. };
  49869. };
  49870. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  49871. var _this = this;
  49872. var numSamples = 16;
  49873. var sampleSphere = [
  49874. 0.5381, 0.1856, -0.4319,
  49875. 0.1379, 0.2486, 0.4430,
  49876. 0.3371, 0.5679, -0.0057,
  49877. -0.6999, -0.0451, -0.0019,
  49878. 0.0689, -0.1598, -0.8547,
  49879. 0.0560, 0.0069, -0.1843,
  49880. -0.0146, 0.1402, 0.0762,
  49881. 0.0100, -0.1924, -0.0344,
  49882. -0.3577, -0.5301, -0.4358,
  49883. -0.3169, 0.1063, 0.0158,
  49884. 0.0103, -0.5869, 0.0046,
  49885. -0.0897, -0.4940, 0.3287,
  49886. 0.7119, -0.0154, -0.0918,
  49887. -0.0533, 0.0596, -0.5411,
  49888. 0.0352, -0.0631, 0.5460,
  49889. -0.4776, 0.2847, -0.0271
  49890. ];
  49891. var samplesFactor = 1.0 / numSamples;
  49892. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  49893. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  49894. "area", "fallOff", "base", "range", "viewport"
  49895. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  49896. var viewport = new BABYLON.Vector2(0, 0);
  49897. this._ssaoPostProcess.onApply = function (effect) {
  49898. if (_this._firstUpdate) {
  49899. effect.setArray3("sampleSphere", sampleSphere);
  49900. effect.setFloat("samplesFactor", samplesFactor);
  49901. effect.setFloat("randTextureTiles", 4.0);
  49902. }
  49903. effect.setFloat("totalStrength", _this.totalStrength);
  49904. effect.setFloat("radius", _this.radius);
  49905. effect.setFloat("area", _this.area);
  49906. effect.setFloat("fallOff", _this.fallOff);
  49907. effect.setFloat("base", _this.base);
  49908. effect.setTexture("textureSampler", _this._depthTexture);
  49909. effect.setTexture("randomSampler", _this._randomTexture);
  49910. };
  49911. };
  49912. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  49913. var _this = this;
  49914. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49915. this._ssaoCombinePostProcess.onApply = function (effect) {
  49916. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  49917. };
  49918. };
  49919. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  49920. var size = 512;
  49921. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  49922. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49923. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49924. var context = this._randomTexture.getContext();
  49925. var rand = function (min, max) {
  49926. return Math.random() * (max - min) + min;
  49927. };
  49928. var randVector = BABYLON.Vector3.Zero();
  49929. for (var x = 0; x < size; x++) {
  49930. for (var y = 0; y < size; y++) {
  49931. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  49932. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  49933. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  49934. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  49935. context.fillRect(x, y, 1, 1);
  49936. }
  49937. }
  49938. this._randomTexture.update(false);
  49939. };
  49940. return SSAORenderingPipeline;
  49941. }(BABYLON.PostProcessRenderPipeline));
  49942. __decorate([
  49943. BABYLON.serialize()
  49944. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  49945. __decorate([
  49946. BABYLON.serialize()
  49947. ], SSAORenderingPipeline.prototype, "radius", void 0);
  49948. __decorate([
  49949. BABYLON.serialize()
  49950. ], SSAORenderingPipeline.prototype, "area", void 0);
  49951. __decorate([
  49952. BABYLON.serialize()
  49953. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  49954. __decorate([
  49955. BABYLON.serialize()
  49956. ], SSAORenderingPipeline.prototype, "base", void 0);
  49957. __decorate([
  49958. BABYLON.serialize()
  49959. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  49960. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  49961. })(BABYLON || (BABYLON = {}));
  49962. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  49963. var BABYLON;
  49964. (function (BABYLON) {
  49965. var SSAO2RenderingPipeline = (function (_super) {
  49966. __extends(SSAO2RenderingPipeline, _super);
  49967. /**
  49968. * @constructor
  49969. * @param {string} name - The rendering pipeline name
  49970. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49971. * @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 }
  49972. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49973. */
  49974. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  49975. var _this = _super.call(this, scene.getEngine(), name) || this;
  49976. // Members
  49977. /**
  49978. * The PassPostProcess id in the pipeline that contains the original scene color
  49979. * @type {string}
  49980. */
  49981. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  49982. /**
  49983. * The SSAO PostProcess id in the pipeline
  49984. * @type {string}
  49985. */
  49986. _this.SSAORenderEffect = "SSAORenderEffect";
  49987. /**
  49988. * The horizontal blur PostProcess id in the pipeline
  49989. * @type {string}
  49990. */
  49991. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  49992. /**
  49993. * The vertical blur PostProcess id in the pipeline
  49994. * @type {string}
  49995. */
  49996. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  49997. /**
  49998. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  49999. * @type {string}
  50000. */
  50001. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  50002. /**
  50003. * The output strength of the SSAO post-process. Default value is 1.0.
  50004. * @type {number}
  50005. */
  50006. _this.totalStrength = 1.0;
  50007. /**
  50008. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  50009. * @type {number}
  50010. */
  50011. _this.maxZ = 100.0;
  50012. /**
  50013. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  50014. * @type {number}
  50015. */
  50016. _this.minZAspect = 0.2;
  50017. /**
  50018. * Number of samples used for the SSAO calculations. Default value is 8
  50019. * @type {number}
  50020. */
  50021. _this._samples = 8;
  50022. /**
  50023. * Are we using bilateral blur ?
  50024. * @type {boolean}
  50025. */
  50026. _this._expensiveBlur = true;
  50027. /**
  50028. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  50029. * @type {number}
  50030. */
  50031. _this.radius = 2.0;
  50032. /**
  50033. * The base color of the SSAO post-process
  50034. * The final result is "base + ssao" between [0, 1]
  50035. * @type {number}
  50036. */
  50037. _this.base = 0.1;
  50038. _this._firstUpdate = true;
  50039. _this._scene = scene;
  50040. if (!_this.isSupported) {
  50041. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  50042. return _this;
  50043. }
  50044. var ssaoRatio = ratio.ssaoRatio || ratio;
  50045. var blurRatio = ratio.blurRatio || ratio;
  50046. _this._ratio = {
  50047. ssaoRatio: ssaoRatio,
  50048. blurRatio: blurRatio
  50049. };
  50050. // Set up assets
  50051. _this._createRandomTexture();
  50052. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  50053. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  50054. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  50055. _this._createSSAOPostProcess(1.0);
  50056. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  50057. _this._createSSAOCombinePostProcess(blurRatio);
  50058. // Set up pipeline
  50059. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  50060. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  50061. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  50062. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  50063. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  50064. // Finish
  50065. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50066. if (cameras)
  50067. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50068. return _this;
  50069. }
  50070. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  50071. get: function () {
  50072. return this._samples;
  50073. },
  50074. set: function (n) {
  50075. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  50076. this._samples = n;
  50077. this._sampleSphere = this._generateHemisphere();
  50078. this._firstUpdate = true;
  50079. },
  50080. enumerable: true,
  50081. configurable: true
  50082. });
  50083. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  50084. get: function () {
  50085. return this._expensiveBlur;
  50086. },
  50087. set: function (b) {
  50088. 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"]);
  50089. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  50090. this._expensiveBlur = b;
  50091. this._firstUpdate = true;
  50092. },
  50093. enumerable: true,
  50094. configurable: true
  50095. });
  50096. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  50097. /**
  50098. * Support test.
  50099. * @type {boolean}
  50100. */
  50101. get: function () {
  50102. var engine = BABYLON.Engine.LastCreatedEngine;
  50103. return engine.webGLVersion > 1;
  50104. },
  50105. enumerable: true,
  50106. configurable: true
  50107. });
  50108. // Public Methods
  50109. /**
  50110. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  50111. */
  50112. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  50113. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  50114. for (var i = 0; i < this._scene.cameras.length; i++) {
  50115. var camera = this._scene.cameras[i];
  50116. this._originalColorPostProcess.dispose(camera);
  50117. this._ssaoPostProcess.dispose(camera);
  50118. this._blurHPostProcess.dispose(camera);
  50119. this._blurVPostProcess.dispose(camera);
  50120. this._ssaoCombinePostProcess.dispose(camera);
  50121. }
  50122. this._randomTexture.dispose();
  50123. if (disableGeometryBufferRenderer)
  50124. this._scene.disableGeometryBufferRenderer();
  50125. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  50126. _super.prototype.dispose.call(this);
  50127. };
  50128. // Private Methods
  50129. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  50130. var _this = this;
  50131. var samples = 16;
  50132. this._samplerOffsets = [];
  50133. var expensive = this.expensiveBlur;
  50134. for (var i = -8; i < 8; i++) {
  50135. this._samplerOffsets.push(i * 2 + 0.5);
  50136. }
  50137. 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");
  50138. this._blurHPostProcess.onApply = function (effect) {
  50139. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  50140. effect.setFloat("near", _this._scene.activeCamera.minZ);
  50141. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  50142. effect.setFloat("radius", _this.radius);
  50143. effect.setTexture("depthSampler", _this._depthTexture);
  50144. if (_this._firstUpdate) {
  50145. effect.setArray("samplerOffsets", _this._samplerOffsets);
  50146. }
  50147. };
  50148. 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");
  50149. this._blurVPostProcess.onApply = function (effect) {
  50150. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  50151. effect.setFloat("near", _this._scene.activeCamera.minZ);
  50152. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  50153. effect.setFloat("radius", _this.radius);
  50154. effect.setTexture("depthSampler", _this._depthTexture);
  50155. if (_this._firstUpdate) {
  50156. effect.setArray("samplerOffsets", _this._samplerOffsets);
  50157. _this._firstUpdate = false;
  50158. }
  50159. };
  50160. };
  50161. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  50162. var numSamples = this.samples;
  50163. var result = [];
  50164. var vector, scale;
  50165. var rand = function (min, max) {
  50166. return Math.random() * (max - min) + min;
  50167. };
  50168. var lerp = function (start, end, percent) {
  50169. return (start + percent * (end - start));
  50170. };
  50171. var i = 0;
  50172. var normal = new BABYLON.Vector3(0, 0, 1);
  50173. while (i < numSamples) {
  50174. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  50175. vector.normalize();
  50176. scale = i / numSamples;
  50177. scale = lerp(0.1, 1.0, scale * scale);
  50178. vector.scaleInPlace(scale);
  50179. result.push(vector.x, vector.y, vector.z);
  50180. i++;
  50181. }
  50182. return result;
  50183. };
  50184. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  50185. var _this = this;
  50186. var numSamples = this.samples;
  50187. this._sampleSphere = this._generateHemisphere();
  50188. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  50189. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  50190. "base", "range", "projection", "near", "far", "texelSize",
  50191. "xViewport", "yViewport", "maxZ", "minZAspect"
  50192. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  50193. this._ssaoPostProcess.onApply = function (effect) {
  50194. if (_this._firstUpdate) {
  50195. effect.setArray3("sampleSphere", _this._sampleSphere);
  50196. effect.setFloat("randTextureTiles", 4.0);
  50197. }
  50198. effect.setFloat("samplesFactor", 1 / _this.samples);
  50199. effect.setFloat("totalStrength", _this.totalStrength);
  50200. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  50201. effect.setFloat("radius", _this.radius);
  50202. effect.setFloat("maxZ", _this.maxZ);
  50203. effect.setFloat("minZAspect", _this.minZAspect);
  50204. effect.setFloat("base", _this.base);
  50205. effect.setFloat("near", _this._scene.activeCamera.minZ);
  50206. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  50207. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.activeCamera.minZ * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  50208. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.activeCamera.minZ);
  50209. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  50210. effect.setTexture("textureSampler", _this._depthTexture);
  50211. effect.setTexture("normalSampler", _this._normalTexture);
  50212. effect.setTexture("randomSampler", _this._randomTexture);
  50213. };
  50214. };
  50215. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  50216. var _this = this;
  50217. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50218. this._ssaoCombinePostProcess.onApply = function (effect) {
  50219. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  50220. };
  50221. };
  50222. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  50223. var size = 512;
  50224. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  50225. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50226. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50227. var context = this._randomTexture.getContext();
  50228. var rand = function (min, max) {
  50229. return Math.random() * (max - min) + min;
  50230. };
  50231. var randVector = BABYLON.Vector3.Zero();
  50232. for (var x = 0; x < size; x++) {
  50233. for (var y = 0; y < size; y++) {
  50234. randVector.x = rand(0.0, 1.0);
  50235. randVector.y = rand(0.0, 1.0);
  50236. randVector.z = 0.0;
  50237. randVector.normalize();
  50238. randVector.scaleInPlace(255);
  50239. randVector.x = Math.floor(randVector.x);
  50240. randVector.y = Math.floor(randVector.y);
  50241. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  50242. context.fillRect(x, y, 1, 1);
  50243. }
  50244. }
  50245. this._randomTexture.update(false);
  50246. };
  50247. return SSAO2RenderingPipeline;
  50248. }(BABYLON.PostProcessRenderPipeline));
  50249. __decorate([
  50250. BABYLON.serialize()
  50251. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  50252. __decorate([
  50253. BABYLON.serialize()
  50254. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  50255. __decorate([
  50256. BABYLON.serialize()
  50257. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  50258. __decorate([
  50259. BABYLON.serialize("samples")
  50260. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  50261. __decorate([
  50262. BABYLON.serialize("expensiveBlur")
  50263. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  50264. __decorate([
  50265. BABYLON.serialize()
  50266. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  50267. __decorate([
  50268. BABYLON.serialize()
  50269. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  50270. __decorate([
  50271. BABYLON.serialize()
  50272. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  50273. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  50274. })(BABYLON || (BABYLON = {}));
  50275. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  50276. // BABYLON.JS Chromatic Aberration GLSL Shader
  50277. // Author: Olivier Guyot
  50278. // Separates very slightly R, G and B colors on the edges of the screen
  50279. // Inspired by Francois Tarlier & Martins Upitis
  50280. var BABYLON;
  50281. (function (BABYLON) {
  50282. var LensRenderingPipeline = (function (_super) {
  50283. __extends(LensRenderingPipeline, _super);
  50284. /**
  50285. * @constructor
  50286. *
  50287. * Effect parameters are as follow:
  50288. * {
  50289. * chromatic_aberration: number; // from 0 to x (1 for realism)
  50290. * edge_blur: number; // from 0 to x (1 for realism)
  50291. * distortion: number; // from 0 to x (1 for realism)
  50292. * grain_amount: number; // from 0 to 1
  50293. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  50294. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  50295. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  50296. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  50297. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  50298. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  50299. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  50300. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  50301. * }
  50302. * Note: if an effect parameter is unset, effect is disabled
  50303. *
  50304. * @param {string} name - The rendering pipeline name
  50305. * @param {object} parameters - An object containing all parameters (see above)
  50306. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50307. * @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)
  50308. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50309. */
  50310. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  50311. if (ratio === void 0) { ratio = 1.0; }
  50312. var _this = _super.call(this, scene.getEngine(), name) || this;
  50313. // Lens effects can be of the following:
  50314. // - chromatic aberration (slight shift of RGB colors)
  50315. // - blur on the edge of the lens
  50316. // - lens distortion
  50317. // - depth-of-field blur & highlights enhancing
  50318. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  50319. // - grain effect (noise or custom texture)
  50320. // Two additional texture samplers are needed:
  50321. // - depth map (for depth-of-field)
  50322. // - grain texture
  50323. /**
  50324. * The chromatic aberration PostProcess id in the pipeline
  50325. * @type {string}
  50326. */
  50327. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  50328. /**
  50329. * The highlights enhancing PostProcess id in the pipeline
  50330. * @type {string}
  50331. */
  50332. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  50333. /**
  50334. * The depth-of-field PostProcess id in the pipeline
  50335. * @type {string}
  50336. */
  50337. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  50338. _this._scene = scene;
  50339. // Fetch texture samplers
  50340. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  50341. if (parameters.grain_texture) {
  50342. _this._grainTexture = parameters.grain_texture;
  50343. }
  50344. else {
  50345. _this._createGrainTexture();
  50346. }
  50347. // save parameters
  50348. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  50349. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  50350. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  50351. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  50352. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  50353. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  50354. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  50355. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  50356. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  50357. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  50358. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  50359. // Create effects
  50360. _this._createChromaticAberrationPostProcess(ratio);
  50361. _this._createHighlightsPostProcess(ratio);
  50362. _this._createDepthOfFieldPostProcess(ratio / 4);
  50363. // Set up pipeline
  50364. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  50365. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  50366. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  50367. if (_this._highlightsGain === -1) {
  50368. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  50369. }
  50370. // Finish
  50371. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50372. if (cameras) {
  50373. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50374. }
  50375. return _this;
  50376. }
  50377. // public methods (self explanatory)
  50378. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  50379. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  50380. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  50381. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  50382. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  50383. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  50384. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  50385. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  50386. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  50387. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  50388. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  50389. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  50390. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  50391. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  50392. };
  50393. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  50394. this._highlightsPostProcess.updateEffect();
  50395. };
  50396. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  50397. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  50398. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  50399. this._highlightsGain = amount;
  50400. };
  50401. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  50402. if (this._highlightsGain === -1) {
  50403. this._highlightsGain = 1.0;
  50404. }
  50405. this._highlightsThreshold = amount;
  50406. };
  50407. LensRenderingPipeline.prototype.disableHighlights = function () {
  50408. this._highlightsGain = -1;
  50409. };
  50410. /**
  50411. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  50412. */
  50413. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  50414. if (disableDepthRender === void 0) { disableDepthRender = false; }
  50415. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  50416. this._chromaticAberrationPostProcess = undefined;
  50417. this._highlightsPostProcess = undefined;
  50418. this._depthOfFieldPostProcess = undefined;
  50419. this._grainTexture.dispose();
  50420. if (disableDepthRender)
  50421. this._scene.disableDepthRenderer();
  50422. };
  50423. // colors shifting and distortion
  50424. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  50425. var _this = this;
  50426. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  50427. [], // samplers
  50428. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50429. this._chromaticAberrationPostProcess.onApply = function (effect) {
  50430. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  50431. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  50432. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  50433. };
  50434. };
  50435. // highlights enhancing
  50436. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  50437. var _this = this;
  50438. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  50439. [], // samplers
  50440. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  50441. this._highlightsPostProcess.onApply = function (effect) {
  50442. effect.setFloat('gain', _this._highlightsGain);
  50443. effect.setFloat('threshold', _this._highlightsThreshold);
  50444. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  50445. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  50446. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  50447. };
  50448. };
  50449. // colors shifting and distortion
  50450. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  50451. var _this = this;
  50452. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  50453. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  50454. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  50455. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50456. this._depthOfFieldPostProcess.onApply = function (effect) {
  50457. effect.setTexture("depthSampler", _this._depthTexture);
  50458. effect.setTexture("grainSampler", _this._grainTexture);
  50459. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  50460. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  50461. effect.setFloat('grain_amount', _this._grainAmount);
  50462. effect.setBool('blur_noise', _this._blurNoise);
  50463. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  50464. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  50465. effect.setFloat('distortion', _this._distortion);
  50466. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  50467. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  50468. effect.setFloat('aperture', _this._dofAperture);
  50469. effect.setFloat('darken', _this._dofDarken);
  50470. effect.setFloat('edge_blur', _this._edgeBlur);
  50471. effect.setBool('highlights', (_this._highlightsGain !== -1));
  50472. effect.setFloat('near', _this._scene.activeCamera.minZ);
  50473. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  50474. };
  50475. };
  50476. // creates a black and white random noise texture, 512x512
  50477. LensRenderingPipeline.prototype._createGrainTexture = function () {
  50478. var size = 512;
  50479. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50480. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50481. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50482. var context = this._grainTexture.getContext();
  50483. var rand = function (min, max) {
  50484. return Math.random() * (max - min) + min;
  50485. };
  50486. var value;
  50487. for (var x = 0; x < size; x++) {
  50488. for (var y = 0; y < size; y++) {
  50489. value = Math.floor(rand(0.42, 0.58) * 255);
  50490. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  50491. context.fillRect(x, y, 1, 1);
  50492. }
  50493. }
  50494. this._grainTexture.update(false);
  50495. };
  50496. return LensRenderingPipeline;
  50497. }(BABYLON.PostProcessRenderPipeline));
  50498. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  50499. })(BABYLON || (BABYLON = {}));
  50500. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  50501. var BABYLON;
  50502. (function (BABYLON) {
  50503. var StandardRenderingPipeline = (function (_super) {
  50504. __extends(StandardRenderingPipeline, _super);
  50505. /**
  50506. * @constructor
  50507. * @param {string} name - The rendering pipeline name
  50508. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50509. * @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)
  50510. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  50511. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50512. */
  50513. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  50514. if (originalPostProcess === void 0) { originalPostProcess = null; }
  50515. var _this = _super.call(this, scene.getEngine(), name) || this;
  50516. _this.downSampleX4PostProcess = null;
  50517. _this.brightPassPostProcess = null;
  50518. _this.blurHPostProcesses = [];
  50519. _this.blurVPostProcesses = [];
  50520. _this.textureAdderPostProcess = null;
  50521. _this.volumetricLightPostProcess = null;
  50522. _this.volumetricLightSmoothXPostProcess = null;
  50523. _this.volumetricLightSmoothYPostProcess = null;
  50524. _this.volumetricLightMergePostProces = null;
  50525. _this.volumetricLightFinalPostProcess = null;
  50526. _this.luminancePostProcess = null;
  50527. _this.luminanceDownSamplePostProcesses = [];
  50528. _this.hdrPostProcess = null;
  50529. _this.textureAdderFinalPostProcess = null;
  50530. _this.lensFlareFinalPostProcess = null;
  50531. _this.hdrFinalPostProcess = null;
  50532. _this.lensFlarePostProcess = null;
  50533. _this.lensFlareComposePostProcess = null;
  50534. _this.motionBlurPostProcess = null;
  50535. _this.depthOfFieldPostProcess = null;
  50536. // Values
  50537. _this.brightThreshold = 1.0;
  50538. _this.blurWidth = 512.0;
  50539. _this.horizontalBlur = false;
  50540. _this.exposure = 1.0;
  50541. _this.lensTexture = null;
  50542. _this.volumetricLightCoefficient = 0.2;
  50543. _this.volumetricLightPower = 4.0;
  50544. _this.volumetricLightBlurScale = 64.0;
  50545. _this.sourceLight = null;
  50546. _this.hdrMinimumLuminance = 1.0;
  50547. _this.hdrDecreaseRate = 0.5;
  50548. _this.hdrIncreaseRate = 0.5;
  50549. _this.lensColorTexture = null;
  50550. _this.lensFlareStrength = 20.0;
  50551. _this.lensFlareGhostDispersal = 1.4;
  50552. _this.lensFlareHaloWidth = 0.7;
  50553. _this.lensFlareDistortionStrength = 16.0;
  50554. _this.lensStarTexture = null;
  50555. _this.lensFlareDirtTexture = null;
  50556. _this.depthOfFieldDistance = 10.0;
  50557. _this.depthOfFieldBlurWidth = 64.0;
  50558. _this.motionStrength = 1.0;
  50559. // IAnimatable
  50560. _this.animations = [];
  50561. _this._currentDepthOfFieldSource = null;
  50562. _this._hdrCurrentLuminance = 1.0;
  50563. // Getters and setters
  50564. _this._bloomEnabled = true;
  50565. _this._depthOfFieldEnabled = false;
  50566. _this._vlsEnabled = false;
  50567. _this._lensFlareEnabled = false;
  50568. _this._hdrEnabled = false;
  50569. _this._motionBlurEnabled = false;
  50570. _this._motionBlurSamples = 64.0;
  50571. _this._volumetricLightStepsCount = 50.0;
  50572. _this._cameras = cameras || [];
  50573. // Initialize
  50574. _this._scene = scene;
  50575. _this._basePostProcess = originalPostProcess;
  50576. _this._ratio = ratio;
  50577. // Misc
  50578. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50579. // Finish
  50580. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50581. _this._buildPipeline();
  50582. return _this;
  50583. }
  50584. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  50585. get: function () {
  50586. return this._bloomEnabled;
  50587. },
  50588. set: function (enabled) {
  50589. if (this._bloomEnabled === enabled) {
  50590. return;
  50591. }
  50592. this._bloomEnabled = enabled;
  50593. this._buildPipeline();
  50594. },
  50595. enumerable: true,
  50596. configurable: true
  50597. });
  50598. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  50599. get: function () {
  50600. return this._depthOfFieldEnabled;
  50601. },
  50602. set: function (enabled) {
  50603. if (this._depthOfFieldEnabled === enabled) {
  50604. return;
  50605. }
  50606. this._depthOfFieldEnabled = enabled;
  50607. this._buildPipeline();
  50608. },
  50609. enumerable: true,
  50610. configurable: true
  50611. });
  50612. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  50613. get: function () {
  50614. return this._lensFlareEnabled;
  50615. },
  50616. set: function (enabled) {
  50617. if (this._lensFlareEnabled === enabled) {
  50618. return;
  50619. }
  50620. this._lensFlareEnabled = enabled;
  50621. this._buildPipeline();
  50622. },
  50623. enumerable: true,
  50624. configurable: true
  50625. });
  50626. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  50627. get: function () {
  50628. return this._hdrEnabled;
  50629. },
  50630. set: function (enabled) {
  50631. if (this._hdrEnabled === enabled) {
  50632. return;
  50633. }
  50634. this._hdrEnabled = enabled;
  50635. this._buildPipeline();
  50636. },
  50637. enumerable: true,
  50638. configurable: true
  50639. });
  50640. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  50641. get: function () {
  50642. return this._vlsEnabled;
  50643. },
  50644. set: function (enabled) {
  50645. if (this._vlsEnabled === enabled) {
  50646. return;
  50647. }
  50648. if (enabled) {
  50649. var geometry = this._scene.enableGeometryBufferRenderer();
  50650. if (!geometry) {
  50651. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  50652. return;
  50653. }
  50654. }
  50655. this._vlsEnabled = enabled;
  50656. this._buildPipeline();
  50657. },
  50658. enumerable: true,
  50659. configurable: true
  50660. });
  50661. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  50662. get: function () {
  50663. return this._motionBlurEnabled;
  50664. },
  50665. set: function (enabled) {
  50666. if (this._motionBlurEnabled === enabled) {
  50667. return;
  50668. }
  50669. this._motionBlurEnabled = enabled;
  50670. this._buildPipeline();
  50671. },
  50672. enumerable: true,
  50673. configurable: true
  50674. });
  50675. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  50676. get: function () {
  50677. return this._volumetricLightStepsCount;
  50678. },
  50679. set: function (count) {
  50680. if (this.volumetricLightPostProcess) {
  50681. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  50682. }
  50683. this._volumetricLightStepsCount = count;
  50684. },
  50685. enumerable: true,
  50686. configurable: true
  50687. });
  50688. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  50689. get: function () {
  50690. return this._motionBlurSamples;
  50691. },
  50692. set: function (samples) {
  50693. if (this.motionBlurPostProcess) {
  50694. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  50695. }
  50696. this._motionBlurSamples = samples;
  50697. },
  50698. enumerable: true,
  50699. configurable: true
  50700. });
  50701. StandardRenderingPipeline.prototype._buildPipeline = function () {
  50702. var _this = this;
  50703. var ratio = this._ratio;
  50704. var scene = this._scene;
  50705. this._disposePostProcesses();
  50706. this._reset();
  50707. // Create pass post-process
  50708. if (!this._basePostProcess) {
  50709. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  50710. this.originalPostProcess.onApply = function (effect) {
  50711. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  50712. };
  50713. }
  50714. else {
  50715. this.originalPostProcess = this._basePostProcess;
  50716. }
  50717. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  50718. this._currentDepthOfFieldSource = this.originalPostProcess;
  50719. if (this._vlsEnabled) {
  50720. // Create volumetric light
  50721. this._createVolumetricLightPostProcess(scene, ratio);
  50722. // Create volumetric light final post-process
  50723. 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);
  50724. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  50725. }
  50726. if (this._bloomEnabled) {
  50727. // Create down sample X4 post-process
  50728. this._createDownSampleX4PostProcess(scene, ratio / 2);
  50729. // Create bright pass post-process
  50730. this._createBrightPassPostProcess(scene, ratio / 2);
  50731. // Create gaussian blur post-processes (down sampling blurs)
  50732. this._createBlurPostProcesses(scene, ratio / 4, 1);
  50733. // Create texture adder post-process
  50734. this._createTextureAdderPostProcess(scene, ratio);
  50735. // Create depth-of-field source post-process
  50736. 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);
  50737. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  50738. }
  50739. if (this._lensFlareEnabled) {
  50740. // Create lens flare post-process
  50741. this._createLensFlarePostProcess(scene, ratio);
  50742. // Create depth-of-field source post-process post lens-flare and disable it now
  50743. 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);
  50744. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  50745. }
  50746. if (this._hdrEnabled) {
  50747. // Create luminance
  50748. this._createLuminancePostProcesses(scene, this._floatTextureType);
  50749. // Create HDR
  50750. this._createHdrPostProcess(scene, ratio);
  50751. // Create depth-of-field source post-process post hdr and disable it now
  50752. 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);
  50753. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  50754. }
  50755. if (this._depthOfFieldEnabled) {
  50756. // Create gaussian blur used by depth-of-field
  50757. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  50758. // Create depth-of-field post-process
  50759. this._createDepthOfFieldPostProcess(scene, ratio);
  50760. }
  50761. if (this._motionBlurEnabled) {
  50762. // Create motion blur post-process
  50763. this._createMotionBlurPostProcess(scene, ratio);
  50764. }
  50765. if (this._cameras !== null) {
  50766. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  50767. }
  50768. };
  50769. // Down Sample X4 Post-Processs
  50770. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  50771. var _this = this;
  50772. var downSampleX4Offsets = new Array(32);
  50773. 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);
  50774. this.downSampleX4PostProcess.onApply = function (effect) {
  50775. var id = 0;
  50776. for (var i = -2; i < 2; i++) {
  50777. for (var j = -2; j < 2; j++) {
  50778. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  50779. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  50780. id += 2;
  50781. }
  50782. }
  50783. effect.setArray2("dsOffsets", downSampleX4Offsets);
  50784. };
  50785. // Add to pipeline
  50786. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  50787. };
  50788. // Brightpass Post-Process
  50789. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  50790. var _this = this;
  50791. var brightOffsets = new Array(8);
  50792. 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);
  50793. this.brightPassPostProcess.onApply = function (effect) {
  50794. var sU = (1.0 / _this.brightPassPostProcess.width);
  50795. var sV = (1.0 / _this.brightPassPostProcess.height);
  50796. brightOffsets[0] = -0.5 * sU;
  50797. brightOffsets[1] = 0.5 * sV;
  50798. brightOffsets[2] = 0.5 * sU;
  50799. brightOffsets[3] = 0.5 * sV;
  50800. brightOffsets[4] = -0.5 * sU;
  50801. brightOffsets[5] = -0.5 * sV;
  50802. brightOffsets[6] = 0.5 * sU;
  50803. brightOffsets[7] = -0.5 * sV;
  50804. effect.setArray2("dsOffsets", brightOffsets);
  50805. effect.setFloat("brightThreshold", _this.brightThreshold);
  50806. };
  50807. // Add to pipeline
  50808. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  50809. };
  50810. // Create blur H&V post-processes
  50811. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  50812. var _this = this;
  50813. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  50814. var engine = scene.getEngine();
  50815. 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);
  50816. 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);
  50817. blurX.onActivateObservable.add(function () {
  50818. var dw = blurX.width / engine.getRenderingCanvas().width;
  50819. blurX.kernel = _this[blurWidthKey] * dw;
  50820. });
  50821. blurY.onActivateObservable.add(function () {
  50822. var dw = blurY.height / engine.getRenderingCanvas().height;
  50823. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  50824. });
  50825. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  50826. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  50827. this.blurHPostProcesses.push(blurX);
  50828. this.blurVPostProcesses.push(blurY);
  50829. };
  50830. // Create texture adder post-process
  50831. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  50832. var _this = this;
  50833. 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);
  50834. this.textureAdderPostProcess.onApply = function (effect) {
  50835. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  50836. effect.setTexture("lensSampler", _this.lensTexture);
  50837. effect.setFloat("exposure", _this.exposure);
  50838. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  50839. };
  50840. // Add to pipeline
  50841. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  50842. };
  50843. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  50844. var _this = this;
  50845. var geometryRenderer = scene.enableGeometryBufferRenderer();
  50846. geometryRenderer.enablePosition = true;
  50847. var geometry = geometryRenderer.getGBuffer();
  50848. // Base post-process
  50849. 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));
  50850. var depthValues = BABYLON.Vector2.Zero();
  50851. this.volumetricLightPostProcess.onApply = function (effect) {
  50852. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  50853. var generator = _this.sourceLight.getShadowGenerator();
  50854. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  50855. effect.setTexture("positionSampler", geometry.textures[2]);
  50856. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  50857. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  50858. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  50859. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  50860. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  50861. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  50862. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  50863. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  50864. effect.setVector2("depthValues", depthValues);
  50865. }
  50866. };
  50867. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  50868. // Smooth
  50869. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  50870. // Merge
  50871. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  50872. this.volumetricLightMergePostProces.onApply = function (effect) {
  50873. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  50874. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  50875. };
  50876. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  50877. };
  50878. // Create luminance
  50879. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  50880. var _this = this;
  50881. // Create luminance
  50882. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  50883. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  50884. var offsets = [];
  50885. this.luminancePostProcess.onApply = function (effect) {
  50886. var sU = (1.0 / _this.luminancePostProcess.width);
  50887. var sV = (1.0 / _this.luminancePostProcess.height);
  50888. offsets[0] = -0.5 * sU;
  50889. offsets[1] = 0.5 * sV;
  50890. offsets[2] = 0.5 * sU;
  50891. offsets[3] = 0.5 * sV;
  50892. offsets[4] = -0.5 * sU;
  50893. offsets[5] = -0.5 * sV;
  50894. offsets[6] = 0.5 * sU;
  50895. offsets[7] = -0.5 * sV;
  50896. effect.setArray2("lumOffsets", offsets);
  50897. };
  50898. // Add to pipeline
  50899. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  50900. // Create down sample luminance
  50901. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  50902. var size = Math.pow(3, i);
  50903. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  50904. if (i === 0) {
  50905. defines += "#define FINAL_DOWN_SAMPLER";
  50906. }
  50907. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  50908. this.luminanceDownSamplePostProcesses.push(postProcess);
  50909. }
  50910. // Create callbacks and add effects
  50911. var lastLuminance = this.luminancePostProcess;
  50912. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  50913. var downSampleOffsets = new Array(18);
  50914. pp.onApply = function (effect) {
  50915. var id = 0;
  50916. for (var x = -1; x < 2; x++) {
  50917. for (var y = -1; y < 2; y++) {
  50918. downSampleOffsets[id] = x / lastLuminance.width;
  50919. downSampleOffsets[id + 1] = y / lastLuminance.height;
  50920. id += 2;
  50921. }
  50922. }
  50923. effect.setArray2("dsOffsets", downSampleOffsets);
  50924. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  50925. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  50926. lastLuminance = _this.luminancePostProcess;
  50927. }
  50928. else {
  50929. lastLuminance = pp;
  50930. }
  50931. };
  50932. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  50933. pp.onAfterRender = function (effect) {
  50934. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  50935. 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);
  50936. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  50937. };
  50938. }
  50939. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  50940. });
  50941. };
  50942. // Create HDR post-process
  50943. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  50944. var _this = this;
  50945. 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);
  50946. var outputLiminance = 1;
  50947. var time = 0;
  50948. var lastTime = 0;
  50949. this.hdrPostProcess.onApply = function (effect) {
  50950. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  50951. time += scene.getEngine().getDeltaTime();
  50952. if (outputLiminance < 0) {
  50953. outputLiminance = _this._hdrCurrentLuminance;
  50954. }
  50955. else {
  50956. var dt = (lastTime - time) / 1000.0;
  50957. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  50958. outputLiminance += _this.hdrDecreaseRate * dt;
  50959. }
  50960. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  50961. outputLiminance -= _this.hdrIncreaseRate * dt;
  50962. }
  50963. else {
  50964. outputLiminance = _this._hdrCurrentLuminance;
  50965. }
  50966. }
  50967. outputLiminance = BABYLON.MathTools.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  50968. effect.setFloat("averageLuminance", outputLiminance);
  50969. lastTime = time;
  50970. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  50971. };
  50972. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  50973. };
  50974. // Create lens flare post-process
  50975. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  50976. var _this = this;
  50977. 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);
  50978. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  50979. this._createBlurPostProcesses(scene, ratio / 4, 2);
  50980. 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);
  50981. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  50982. var resolution = new BABYLON.Vector2(0, 0);
  50983. // Lens flare
  50984. this.lensFlarePostProcess.onApply = function (effect) {
  50985. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  50986. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  50987. effect.setFloat("strength", _this.lensFlareStrength);
  50988. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  50989. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  50990. // Shift
  50991. resolution.x = _this.lensFlarePostProcess.width;
  50992. resolution.y = _this.lensFlarePostProcess.height;
  50993. effect.setVector2("resolution", resolution);
  50994. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  50995. };
  50996. // Compose
  50997. 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);
  50998. 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);
  50999. this.lensFlareComposePostProcess.onApply = function (effect) {
  51000. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  51001. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  51002. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  51003. // Lens start rotation matrix
  51004. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  51005. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  51006. 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));
  51007. camRot *= 4.0;
  51008. 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);
  51009. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  51010. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  51011. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  51012. };
  51013. };
  51014. // Create depth-of-field post-process
  51015. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  51016. var _this = this;
  51017. 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);
  51018. this.depthOfFieldPostProcess.onApply = function (effect) {
  51019. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  51020. effect.setTexture("depthSampler", _this._getDepthTexture());
  51021. effect.setFloat("distance", _this.depthOfFieldDistance);
  51022. };
  51023. // Add to pipeline
  51024. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  51025. };
  51026. // Create motion blur post-process
  51027. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  51028. var _this = this;
  51029. 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);
  51030. var motionScale = 0;
  51031. var prevViewProjection = BABYLON.Matrix.Identity();
  51032. var invViewProjection = BABYLON.Matrix.Identity();
  51033. var viewProjection = BABYLON.Matrix.Identity();
  51034. var screenSize = BABYLON.Vector2.Zero();
  51035. this.motionBlurPostProcess.onApply = function (effect) {
  51036. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  51037. viewProjection.invertToRef(invViewProjection);
  51038. effect.setMatrix("inverseViewProjection", invViewProjection);
  51039. effect.setMatrix("prevViewProjection", prevViewProjection);
  51040. prevViewProjection = viewProjection;
  51041. screenSize.x = _this.motionBlurPostProcess.width;
  51042. screenSize.y = _this.motionBlurPostProcess.height;
  51043. effect.setVector2("screenSize", screenSize);
  51044. motionScale = scene.getEngine().getFps() / 60.0;
  51045. effect.setFloat("motionScale", motionScale);
  51046. effect.setFloat("motionStrength", _this.motionStrength);
  51047. effect.setTexture("depthSampler", _this._getDepthTexture());
  51048. };
  51049. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  51050. };
  51051. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  51052. var geometry = this._scene.enableGeometryBufferRenderer();
  51053. if (geometry) {
  51054. return geometry.getGBuffer().textures[0];
  51055. }
  51056. return this._scene.enableDepthRenderer().getDepthMap();
  51057. };
  51058. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  51059. for (var i = 0; i < this._cameras.length; i++) {
  51060. var camera = this._cameras[i];
  51061. if (this.originalPostProcess) {
  51062. this.originalPostProcess.dispose(camera);
  51063. }
  51064. if (this.downSampleX4PostProcess) {
  51065. this.downSampleX4PostProcess.dispose(camera);
  51066. }
  51067. if (this.brightPassPostProcess) {
  51068. this.brightPassPostProcess.dispose(camera);
  51069. }
  51070. if (this.textureAdderPostProcess) {
  51071. this.textureAdderPostProcess.dispose(camera);
  51072. }
  51073. if (this.textureAdderFinalPostProcess) {
  51074. this.textureAdderFinalPostProcess.dispose(camera);
  51075. }
  51076. if (this.volumetricLightPostProcess) {
  51077. this.volumetricLightPostProcess.dispose(camera);
  51078. }
  51079. if (this.volumetricLightSmoothXPostProcess) {
  51080. this.volumetricLightSmoothXPostProcess.dispose(camera);
  51081. }
  51082. if (this.volumetricLightSmoothYPostProcess) {
  51083. this.volumetricLightSmoothYPostProcess.dispose(camera);
  51084. }
  51085. if (this.volumetricLightMergePostProces) {
  51086. this.volumetricLightMergePostProces.dispose(camera);
  51087. }
  51088. if (this.volumetricLightFinalPostProcess) {
  51089. this.volumetricLightFinalPostProcess.dispose(camera);
  51090. }
  51091. if (this.lensFlarePostProcess) {
  51092. this.lensFlarePostProcess.dispose(camera);
  51093. }
  51094. if (this.lensFlareComposePostProcess) {
  51095. this.lensFlareComposePostProcess.dispose(camera);
  51096. }
  51097. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  51098. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  51099. }
  51100. if (this.luminancePostProcess) {
  51101. this.luminancePostProcess.dispose(camera);
  51102. }
  51103. if (this.hdrPostProcess) {
  51104. this.hdrPostProcess.dispose(camera);
  51105. }
  51106. if (this.hdrFinalPostProcess) {
  51107. this.hdrFinalPostProcess.dispose(camera);
  51108. }
  51109. if (this.depthOfFieldPostProcess) {
  51110. this.depthOfFieldPostProcess.dispose(camera);
  51111. }
  51112. if (this.motionBlurPostProcess) {
  51113. this.motionBlurPostProcess.dispose(camera);
  51114. }
  51115. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  51116. this.blurHPostProcesses[j].dispose(camera);
  51117. }
  51118. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  51119. this.blurVPostProcesses[j].dispose(camera);
  51120. }
  51121. }
  51122. this.originalPostProcess = null;
  51123. this.downSampleX4PostProcess = null;
  51124. this.brightPassPostProcess = null;
  51125. this.textureAdderPostProcess = null;
  51126. this.textureAdderFinalPostProcess = null;
  51127. this.volumetricLightPostProcess = null;
  51128. this.volumetricLightSmoothXPostProcess = null;
  51129. this.volumetricLightSmoothYPostProcess = null;
  51130. this.volumetricLightMergePostProces = null;
  51131. this.volumetricLightFinalPostProcess = null;
  51132. this.lensFlarePostProcess = null;
  51133. this.lensFlareComposePostProcess = null;
  51134. this.luminancePostProcess = null;
  51135. this.hdrPostProcess = null;
  51136. this.hdrFinalPostProcess = null;
  51137. this.depthOfFieldPostProcess = null;
  51138. this.motionBlurPostProcess = null;
  51139. this.luminanceDownSamplePostProcesses = [];
  51140. this.blurHPostProcesses = [];
  51141. this.blurVPostProcesses = [];
  51142. };
  51143. // Dispose
  51144. StandardRenderingPipeline.prototype.dispose = function () {
  51145. this._disposePostProcesses();
  51146. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  51147. _super.prototype.dispose.call(this);
  51148. };
  51149. // Serialize rendering pipeline
  51150. StandardRenderingPipeline.prototype.serialize = function () {
  51151. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51152. serializationObject.customType = "StandardRenderingPipeline";
  51153. return serializationObject;
  51154. };
  51155. /**
  51156. * Static members
  51157. */
  51158. // Parse serialized pipeline
  51159. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  51160. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  51161. };
  51162. return StandardRenderingPipeline;
  51163. }(BABYLON.PostProcessRenderPipeline));
  51164. // Luminance steps
  51165. StandardRenderingPipeline.LuminanceSteps = 6;
  51166. __decorate([
  51167. BABYLON.serialize()
  51168. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  51169. __decorate([
  51170. BABYLON.serialize()
  51171. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  51172. __decorate([
  51173. BABYLON.serialize()
  51174. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  51175. __decorate([
  51176. BABYLON.serialize()
  51177. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  51178. __decorate([
  51179. BABYLON.serializeAsTexture("lensTexture")
  51180. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  51181. __decorate([
  51182. BABYLON.serialize()
  51183. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  51184. __decorate([
  51185. BABYLON.serialize()
  51186. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  51187. __decorate([
  51188. BABYLON.serialize()
  51189. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  51190. __decorate([
  51191. BABYLON.serialize()
  51192. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  51193. __decorate([
  51194. BABYLON.serialize()
  51195. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  51196. __decorate([
  51197. BABYLON.serialize()
  51198. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  51199. __decorate([
  51200. BABYLON.serializeAsTexture("lensColorTexture")
  51201. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  51202. __decorate([
  51203. BABYLON.serialize()
  51204. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  51205. __decorate([
  51206. BABYLON.serialize()
  51207. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  51208. __decorate([
  51209. BABYLON.serialize()
  51210. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  51211. __decorate([
  51212. BABYLON.serialize()
  51213. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  51214. __decorate([
  51215. BABYLON.serializeAsTexture("lensStarTexture")
  51216. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  51217. __decorate([
  51218. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  51219. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  51220. __decorate([
  51221. BABYLON.serialize()
  51222. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  51223. __decorate([
  51224. BABYLON.serialize()
  51225. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  51226. __decorate([
  51227. BABYLON.serialize()
  51228. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  51229. __decorate([
  51230. BABYLON.serialize()
  51231. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  51232. __decorate([
  51233. BABYLON.serialize()
  51234. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  51235. __decorate([
  51236. BABYLON.serialize()
  51237. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  51238. __decorate([
  51239. BABYLON.serialize()
  51240. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  51241. __decorate([
  51242. BABYLON.serialize()
  51243. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  51244. __decorate([
  51245. BABYLON.serialize()
  51246. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  51247. __decorate([
  51248. BABYLON.serialize()
  51249. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  51250. __decorate([
  51251. BABYLON.serialize()
  51252. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  51253. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  51254. })(BABYLON || (BABYLON = {}));
  51255. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  51256. var BABYLON;
  51257. (function (BABYLON) {
  51258. var FxaaPostProcess = (function (_super) {
  51259. __extends(FxaaPostProcess, _super);
  51260. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  51261. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51262. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  51263. _this.onApplyObservable.add(function (effect) {
  51264. var texelSize = _this.texelSize;
  51265. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  51266. });
  51267. return _this;
  51268. }
  51269. return FxaaPostProcess;
  51270. }(BABYLON.PostProcess));
  51271. BABYLON.FxaaPostProcess = FxaaPostProcess;
  51272. })(BABYLON || (BABYLON = {}));
  51273. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  51274. var BABYLON;
  51275. (function (BABYLON) {
  51276. var DefaultRenderingPipeline = (function (_super) {
  51277. __extends(DefaultRenderingPipeline, _super);
  51278. /**
  51279. * @constructor
  51280. * @param {string} name - The rendering pipeline name
  51281. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51282. * @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)
  51283. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51284. */
  51285. function DefaultRenderingPipeline(name, hdr, scene, cameras) {
  51286. var _this = _super.call(this, scene.getEngine(), name) || this;
  51287. _this.PassPostProcessId = "PassPostProcessEffect";
  51288. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  51289. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  51290. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  51291. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  51292. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  51293. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  51294. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  51295. // IAnimatable
  51296. _this.animations = [];
  51297. // Values
  51298. _this._bloomEnabled = false;
  51299. _this._fxaaEnabled = false;
  51300. _this._imageProcessingEnabled = true;
  51301. _this._bloomScale = 0.6;
  51302. /**
  51303. * Specifies the size of the bloom blur kernel, relative to the final output size
  51304. */
  51305. _this.bloomKernel = 64;
  51306. /**
  51307. * Specifies the weight of the bloom in the final rendering
  51308. */
  51309. _this._bloomWeight = 0.15;
  51310. _this._cameras = cameras || [];
  51311. // Initialize
  51312. _this._scene = scene;
  51313. var caps = _this._scene.getEngine().getCaps();
  51314. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  51315. // Misc
  51316. if (_this._hdr) {
  51317. if (caps.textureHalfFloatRender) {
  51318. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51319. }
  51320. else if (caps.textureFloatRender) {
  51321. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51322. }
  51323. }
  51324. else {
  51325. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51326. }
  51327. // Attach
  51328. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51329. _this._buildPipeline();
  51330. return _this;
  51331. }
  51332. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  51333. get: function () {
  51334. return this._bloomWeight;
  51335. },
  51336. set: function (value) {
  51337. if (this._bloomWeight === value) {
  51338. return;
  51339. }
  51340. this._bloomWeight = value;
  51341. if (this._hdr && this.copyBack) {
  51342. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  51343. }
  51344. },
  51345. enumerable: true,
  51346. configurable: true
  51347. });
  51348. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  51349. get: function () {
  51350. return this._bloomScale;
  51351. },
  51352. set: function (value) {
  51353. if (this._bloomScale === value) {
  51354. return;
  51355. }
  51356. this._bloomScale = value;
  51357. this._buildPipeline();
  51358. },
  51359. enumerable: true,
  51360. configurable: true
  51361. });
  51362. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  51363. get: function () {
  51364. return this._bloomEnabled;
  51365. },
  51366. set: function (enabled) {
  51367. if (this._bloomEnabled === enabled) {
  51368. return;
  51369. }
  51370. this._bloomEnabled = enabled;
  51371. this._buildPipeline();
  51372. },
  51373. enumerable: true,
  51374. configurable: true
  51375. });
  51376. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  51377. get: function () {
  51378. return this._fxaaEnabled;
  51379. },
  51380. set: function (enabled) {
  51381. if (this._fxaaEnabled === enabled) {
  51382. return;
  51383. }
  51384. this._fxaaEnabled = enabled;
  51385. this._buildPipeline();
  51386. },
  51387. enumerable: true,
  51388. configurable: true
  51389. });
  51390. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  51391. get: function () {
  51392. return this._imageProcessingEnabled;
  51393. },
  51394. set: function (enabled) {
  51395. if (this._imageProcessingEnabled === enabled) {
  51396. return;
  51397. }
  51398. this._imageProcessingEnabled = enabled;
  51399. this._buildPipeline();
  51400. },
  51401. enumerable: true,
  51402. configurable: true
  51403. });
  51404. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  51405. var _this = this;
  51406. var engine = this._scene.getEngine();
  51407. this._disposePostProcesses();
  51408. this._reset();
  51409. if (this.bloomEnabled) {
  51410. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51411. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  51412. if (!this._hdr) {
  51413. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51414. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  51415. this.highlights.autoClear = false;
  51416. this.highlights.alwaysForcePOT = true;
  51417. }
  51418. 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);
  51419. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  51420. this.blurX.alwaysForcePOT = true;
  51421. this.blurX.autoClear = false;
  51422. this.blurX.onActivateObservable.add(function () {
  51423. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  51424. _this.blurX.kernel = _this.bloomKernel * dw;
  51425. });
  51426. 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);
  51427. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  51428. this.blurY.alwaysForcePOT = true;
  51429. this.blurY.autoClear = false;
  51430. this.blurY.onActivateObservable.add(function () {
  51431. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  51432. _this.blurY.kernel = _this.bloomKernel * dh;
  51433. });
  51434. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51435. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  51436. this.copyBack.alwaysForcePOT = true;
  51437. if (this._hdr) {
  51438. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  51439. var w = this.bloomWeight;
  51440. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  51441. }
  51442. else {
  51443. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  51444. }
  51445. this.copyBack.autoClear = false;
  51446. }
  51447. if (this._imageProcessingEnabled) {
  51448. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51449. if (this._hdr) {
  51450. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  51451. }
  51452. }
  51453. if (this.fxaaEnabled) {
  51454. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51455. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  51456. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  51457. }
  51458. else {
  51459. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  51460. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  51461. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  51462. }
  51463. if (this.bloomEnabled) {
  51464. if (this._hdr) {
  51465. this.copyBack.shareOutputWith(this.blurX);
  51466. if (this.imageProcessing) {
  51467. this.imageProcessing.shareOutputWith(this.pass);
  51468. this.imageProcessing.autoClear = false;
  51469. }
  51470. else if (this.fxaa) {
  51471. this.fxaa.shareOutputWith(this.pass);
  51472. }
  51473. else {
  51474. this.finalMerge.shareOutputWith(this.pass);
  51475. }
  51476. }
  51477. else {
  51478. if (this.fxaa) {
  51479. this.fxaa.shareOutputWith(this.pass);
  51480. }
  51481. else {
  51482. this.finalMerge.shareOutputWith(this.pass);
  51483. }
  51484. }
  51485. }
  51486. if (this._cameras !== null) {
  51487. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  51488. }
  51489. };
  51490. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  51491. for (var i = 0; i < this._cameras.length; i++) {
  51492. var camera = this._cameras[i];
  51493. if (this.pass) {
  51494. this.pass.dispose(camera);
  51495. }
  51496. if (this.highlights) {
  51497. this.highlights.dispose(camera);
  51498. }
  51499. if (this.blurX) {
  51500. this.blurX.dispose(camera);
  51501. }
  51502. if (this.blurY) {
  51503. this.blurY.dispose(camera);
  51504. }
  51505. if (this.copyBack) {
  51506. this.copyBack.dispose(camera);
  51507. }
  51508. if (this.imageProcessing) {
  51509. this.imageProcessing.dispose(camera);
  51510. }
  51511. if (this.fxaa) {
  51512. this.fxaa.dispose(camera);
  51513. }
  51514. if (this.finalMerge) {
  51515. this.finalMerge.dispose(camera);
  51516. }
  51517. }
  51518. this.pass = null;
  51519. this.highlights = null;
  51520. this.blurX = null;
  51521. this.blurY = null;
  51522. this.copyBack = null;
  51523. this.imageProcessing = null;
  51524. this.fxaa = null;
  51525. this.finalMerge = null;
  51526. };
  51527. // Dispose
  51528. DefaultRenderingPipeline.prototype.dispose = function () {
  51529. this._disposePostProcesses();
  51530. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  51531. _super.prototype.dispose.call(this);
  51532. };
  51533. // Serialize rendering pipeline
  51534. DefaultRenderingPipeline.prototype.serialize = function () {
  51535. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51536. serializationObject.customType = "DefaultRenderingPipeline";
  51537. return serializationObject;
  51538. };
  51539. // Parse serialized pipeline
  51540. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  51541. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  51542. };
  51543. return DefaultRenderingPipeline;
  51544. }(BABYLON.PostProcessRenderPipeline));
  51545. __decorate([
  51546. BABYLON.serialize()
  51547. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  51548. __decorate([
  51549. BABYLON.serialize()
  51550. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  51551. __decorate([
  51552. BABYLON.serialize()
  51553. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  51554. __decorate([
  51555. BABYLON.serialize()
  51556. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  51557. __decorate([
  51558. BABYLON.serialize()
  51559. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  51560. __decorate([
  51561. BABYLON.serialize()
  51562. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  51563. __decorate([
  51564. BABYLON.serialize()
  51565. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  51566. __decorate([
  51567. BABYLON.serialize()
  51568. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  51569. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  51570. })(BABYLON || (BABYLON = {}));
  51571. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  51572. var BABYLON;
  51573. (function (BABYLON) {
  51574. var GeometryBufferRenderer = (function () {
  51575. function GeometryBufferRenderer(scene, ratio) {
  51576. if (ratio === void 0) { ratio = 1; }
  51577. this._viewMatrix = BABYLON.Matrix.Zero();
  51578. this._projectionMatrix = BABYLON.Matrix.Zero();
  51579. this._transformMatrix = BABYLON.Matrix.Zero();
  51580. this._worldViewProjection = BABYLON.Matrix.Zero();
  51581. this._enablePosition = false;
  51582. this._scene = scene;
  51583. this._ratio = ratio;
  51584. // Render target
  51585. this._createRenderTargets();
  51586. }
  51587. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  51588. set: function (meshes) {
  51589. this._multiRenderTarget.renderList = meshes;
  51590. },
  51591. enumerable: true,
  51592. configurable: true
  51593. });
  51594. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  51595. get: function () {
  51596. return this._multiRenderTarget.isSupported;
  51597. },
  51598. enumerable: true,
  51599. configurable: true
  51600. });
  51601. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  51602. get: function () {
  51603. return this._enablePosition;
  51604. },
  51605. set: function (enable) {
  51606. this._enablePosition = enable;
  51607. this.dispose();
  51608. this._createRenderTargets();
  51609. },
  51610. enumerable: true,
  51611. configurable: true
  51612. });
  51613. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  51614. var material = subMesh.getMaterial();
  51615. if (material && material.disableDepthWrite) {
  51616. return false;
  51617. }
  51618. var defines = [];
  51619. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  51620. var mesh = subMesh.getMesh();
  51621. var scene = mesh.getScene();
  51622. // Alpha test
  51623. if (material && material.needAlphaTesting()) {
  51624. defines.push("#define ALPHATEST");
  51625. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51626. attribs.push(BABYLON.VertexBuffer.UVKind);
  51627. defines.push("#define UV1");
  51628. }
  51629. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51630. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51631. defines.push("#define UV2");
  51632. }
  51633. }
  51634. // Buffers
  51635. if (this._enablePosition) {
  51636. defines.push("#define POSITION");
  51637. }
  51638. // Bones
  51639. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51640. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51641. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51642. if (mesh.numBoneInfluencers > 4) {
  51643. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51644. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51645. }
  51646. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51647. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51648. }
  51649. else {
  51650. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51651. }
  51652. // Instances
  51653. if (useInstances) {
  51654. defines.push("#define INSTANCES");
  51655. attribs.push("world0");
  51656. attribs.push("world1");
  51657. attribs.push("world2");
  51658. attribs.push("world3");
  51659. }
  51660. // Get correct effect
  51661. var join = defines.join("\n");
  51662. if (this._cachedDefines !== join) {
  51663. this._cachedDefines = join;
  51664. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join);
  51665. }
  51666. return this._effect.isReady();
  51667. };
  51668. GeometryBufferRenderer.prototype.getGBuffer = function () {
  51669. return this._multiRenderTarget;
  51670. };
  51671. // Methods
  51672. GeometryBufferRenderer.prototype.dispose = function () {
  51673. this.getGBuffer().dispose();
  51674. };
  51675. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  51676. var _this = this;
  51677. var engine = this._scene.getEngine();
  51678. var count = this._enablePosition ? 3 : 2;
  51679. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  51680. if (!this.isSupported) {
  51681. return null;
  51682. }
  51683. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51684. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51685. this._multiRenderTarget.refreshRate = 1;
  51686. this._multiRenderTarget.renderParticles = false;
  51687. this._multiRenderTarget.renderList = null;
  51688. // set default depth value to 1.0 (far away)
  51689. this._multiRenderTarget.onClearObservable.add(function (engine) {
  51690. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  51691. });
  51692. // Custom render function
  51693. var renderSubMesh = function (subMesh) {
  51694. var mesh = subMesh.getRenderingMesh();
  51695. var scene = _this._scene;
  51696. var engine = scene.getEngine();
  51697. // Culling
  51698. engine.setState(subMesh.getMaterial().backFaceCulling);
  51699. // Managing instances
  51700. var batch = mesh._getInstancesRenderList(subMesh._id);
  51701. if (batch.mustReturn) {
  51702. return;
  51703. }
  51704. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  51705. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  51706. engine.enableEffect(_this._effect);
  51707. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  51708. var material = subMesh.getMaterial();
  51709. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  51710. _this._effect.setMatrix("view", scene.getViewMatrix());
  51711. // Alpha test
  51712. if (material && material.needAlphaTesting()) {
  51713. var alphaTexture = material.getAlphaTestTexture();
  51714. _this._effect.setTexture("diffuseSampler", alphaTexture);
  51715. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  51716. }
  51717. // Bones
  51718. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51719. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  51720. }
  51721. // Draw
  51722. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51723. }
  51724. };
  51725. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  51726. var index;
  51727. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51728. renderSubMesh(opaqueSubMeshes.data[index]);
  51729. }
  51730. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51731. renderSubMesh(alphaTestSubMeshes.data[index]);
  51732. }
  51733. };
  51734. };
  51735. return GeometryBufferRenderer;
  51736. }());
  51737. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  51738. })(BABYLON || (BABYLON = {}));
  51739. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  51740. var BABYLON;
  51741. (function (BABYLON) {
  51742. var RefractionPostProcess = (function (_super) {
  51743. __extends(RefractionPostProcess, _super);
  51744. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  51745. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  51746. _this.color = color;
  51747. _this.depth = depth;
  51748. _this.colorLevel = colorLevel;
  51749. _this.onActivateObservable.add(function (cam) {
  51750. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  51751. });
  51752. _this.onApplyObservable.add(function (effect) {
  51753. effect.setColor3("baseColor", _this.color);
  51754. effect.setFloat("depth", _this.depth);
  51755. effect.setFloat("colorLevel", _this.colorLevel);
  51756. effect.setTexture("refractionSampler", _this._refRexture);
  51757. });
  51758. return _this;
  51759. }
  51760. // Methods
  51761. RefractionPostProcess.prototype.dispose = function (camera) {
  51762. if (this._refRexture) {
  51763. this._refRexture.dispose();
  51764. }
  51765. _super.prototype.dispose.call(this, camera);
  51766. };
  51767. return RefractionPostProcess;
  51768. }(BABYLON.PostProcess));
  51769. BABYLON.RefractionPostProcess = RefractionPostProcess;
  51770. })(BABYLON || (BABYLON = {}));
  51771. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  51772. var BABYLON;
  51773. (function (BABYLON) {
  51774. var BlackAndWhitePostProcess = (function (_super) {
  51775. __extends(BlackAndWhitePostProcess, _super);
  51776. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  51777. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  51778. _this.degree = 1;
  51779. _this.onApplyObservable.add(function (effect) {
  51780. effect.setFloat("degree", _this.degree);
  51781. });
  51782. return _this;
  51783. }
  51784. return BlackAndWhitePostProcess;
  51785. }(BABYLON.PostProcess));
  51786. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  51787. })(BABYLON || (BABYLON = {}));
  51788. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  51789. var BABYLON;
  51790. (function (BABYLON) {
  51791. var ConvolutionPostProcess = (function (_super) {
  51792. __extends(ConvolutionPostProcess, _super);
  51793. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  51794. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  51795. _this.kernel = kernel;
  51796. _this.onApply = function (effect) {
  51797. effect.setFloat2("screenSize", _this.width, _this.height);
  51798. effect.setArray("kernel", _this.kernel);
  51799. };
  51800. return _this;
  51801. }
  51802. return ConvolutionPostProcess;
  51803. }(BABYLON.PostProcess));
  51804. // Statics
  51805. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  51806. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  51807. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  51808. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  51809. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  51810. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  51811. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  51812. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  51813. })(BABYLON || (BABYLON = {}));
  51814. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  51815. var BABYLON;
  51816. (function (BABYLON) {
  51817. var FilterPostProcess = (function (_super) {
  51818. __extends(FilterPostProcess, _super);
  51819. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  51820. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  51821. _this.kernelMatrix = kernelMatrix;
  51822. _this.onApply = function (effect) {
  51823. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  51824. };
  51825. return _this;
  51826. }
  51827. return FilterPostProcess;
  51828. }(BABYLON.PostProcess));
  51829. BABYLON.FilterPostProcess = FilterPostProcess;
  51830. })(BABYLON || (BABYLON = {}));
  51831. //# sourceMappingURL=babylon.filterPostProcess.js.map
  51832. var BABYLON;
  51833. (function (BABYLON) {
  51834. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  51835. var VolumetricLightScatteringPostProcess = (function (_super) {
  51836. __extends(VolumetricLightScatteringPostProcess, _super);
  51837. /**
  51838. * @constructor
  51839. * @param {string} name - The post-process name
  51840. * @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)
  51841. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  51842. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  51843. * @param {number} samples - The post-process quality, default 100
  51844. * @param {number} samplingMode - The post-process filtering mode
  51845. * @param {BABYLON.Engine} engine - The babylon engine
  51846. * @param {boolean} reusable - If the post-process is reusable
  51847. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  51848. */
  51849. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  51850. if (samples === void 0) { samples = 100; }
  51851. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51852. 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;
  51853. _this._screenCoordinates = BABYLON.Vector2.Zero();
  51854. /**
  51855. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  51856. * @type {Vector3}
  51857. */
  51858. _this.customMeshPosition = BABYLON.Vector3.Zero();
  51859. /**
  51860. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  51861. * @type {boolean}
  51862. */
  51863. _this.useCustomMeshPosition = false;
  51864. /**
  51865. * If the post-process should inverse the light scattering direction
  51866. * @type {boolean}
  51867. */
  51868. _this.invert = true;
  51869. /**
  51870. * Array containing the excluded meshes not rendered in the internal pass
  51871. */
  51872. _this.excludedMeshes = new Array();
  51873. /**
  51874. * Controls the overall intensity of the post-process
  51875. * @type {number}
  51876. */
  51877. _this.exposure = 0.3;
  51878. /**
  51879. * Dissipates each sample's contribution in range [0, 1]
  51880. * @type {number}
  51881. */
  51882. _this.decay = 0.96815;
  51883. /**
  51884. * Controls the overall intensity of each sample
  51885. * @type {number}
  51886. */
  51887. _this.weight = 0.58767;
  51888. /**
  51889. * Controls the density of each sample
  51890. * @type {number}
  51891. */
  51892. _this.density = 0.926;
  51893. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  51894. var engine = scene.getEngine();
  51895. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  51896. // Configure mesh
  51897. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  51898. // Configure
  51899. _this._createPass(scene, ratio.passRatio || ratio);
  51900. _this.onActivate = function (camera) {
  51901. if (!_this.isSupported) {
  51902. _this.dispose(camera);
  51903. }
  51904. _this.onActivate = null;
  51905. };
  51906. _this.onApplyObservable.add(function (effect) {
  51907. _this._updateMeshScreenCoordinates(scene);
  51908. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  51909. effect.setFloat("exposure", _this.exposure);
  51910. effect.setFloat("decay", _this.decay);
  51911. effect.setFloat("weight", _this.weight);
  51912. effect.setFloat("density", _this.density);
  51913. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  51914. });
  51915. return _this;
  51916. }
  51917. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  51918. get: function () {
  51919. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  51920. return false;
  51921. },
  51922. set: function (useDiffuseColor) {
  51923. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  51924. },
  51925. enumerable: true,
  51926. configurable: true
  51927. });
  51928. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  51929. var mesh = subMesh.getMesh();
  51930. // Render this.mesh as default
  51931. if (mesh === this.mesh) {
  51932. return mesh.material.isReady(mesh);
  51933. }
  51934. var defines = [];
  51935. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51936. var material = subMesh.getMaterial();
  51937. var needUV = false;
  51938. // Alpha test
  51939. if (material) {
  51940. if (material.needAlphaTesting()) {
  51941. defines.push("#define ALPHATEST");
  51942. }
  51943. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51944. attribs.push(BABYLON.VertexBuffer.UVKind);
  51945. defines.push("#define UV1");
  51946. }
  51947. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51948. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51949. defines.push("#define UV2");
  51950. }
  51951. }
  51952. // Bones
  51953. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51954. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51955. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51956. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51957. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51958. }
  51959. else {
  51960. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51961. }
  51962. // Instances
  51963. if (useInstances) {
  51964. defines.push("#define INSTANCES");
  51965. attribs.push("world0");
  51966. attribs.push("world1");
  51967. attribs.push("world2");
  51968. attribs.push("world3");
  51969. }
  51970. // Get correct effect
  51971. var join = defines.join("\n");
  51972. if (this._cachedDefines !== join) {
  51973. this._cachedDefines = join;
  51974. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  51975. }
  51976. return this._volumetricLightScatteringPass.isReady();
  51977. };
  51978. /**
  51979. * Sets the new light position for light scattering effect
  51980. * @param {BABYLON.Vector3} The new custom light position
  51981. */
  51982. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  51983. this.customMeshPosition = position;
  51984. };
  51985. /**
  51986. * Returns the light position for light scattering effect
  51987. * @return {BABYLON.Vector3} The custom light position
  51988. */
  51989. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  51990. return this.customMeshPosition;
  51991. };
  51992. /**
  51993. * Disposes the internal assets and detaches the post-process from the camera
  51994. */
  51995. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  51996. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  51997. if (rttIndex !== -1) {
  51998. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  51999. }
  52000. this._volumetricLightScatteringRTT.dispose();
  52001. _super.prototype.dispose.call(this, camera);
  52002. };
  52003. /**
  52004. * Returns the render target texture used by the post-process
  52005. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  52006. */
  52007. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  52008. return this._volumetricLightScatteringRTT;
  52009. };
  52010. // Private methods
  52011. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  52012. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  52013. return true;
  52014. }
  52015. return false;
  52016. };
  52017. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  52018. var _this = this;
  52019. var engine = scene.getEngine();
  52020. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52021. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52022. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52023. this._volumetricLightScatteringRTT.renderList = null;
  52024. this._volumetricLightScatteringRTT.renderParticles = false;
  52025. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  52026. // Custom render function for submeshes
  52027. var renderSubMesh = function (subMesh) {
  52028. var mesh = subMesh.getRenderingMesh();
  52029. if (_this._meshExcluded(mesh)) {
  52030. return;
  52031. }
  52032. var scene = mesh.getScene();
  52033. var engine = scene.getEngine();
  52034. // Culling
  52035. engine.setState(subMesh.getMaterial().backFaceCulling);
  52036. // Managing instances
  52037. var batch = mesh._getInstancesRenderList(subMesh._id);
  52038. if (batch.mustReturn) {
  52039. return;
  52040. }
  52041. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  52042. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52043. var effect = _this._volumetricLightScatteringPass;
  52044. if (mesh === _this.mesh) {
  52045. if (subMesh.effect) {
  52046. effect = subMesh.effect;
  52047. }
  52048. else {
  52049. effect = subMesh.getMaterial().getEffect();
  52050. }
  52051. }
  52052. engine.enableEffect(effect);
  52053. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  52054. if (mesh === _this.mesh) {
  52055. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  52056. }
  52057. else {
  52058. var material = subMesh.getMaterial();
  52059. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  52060. // Alpha test
  52061. if (material && material.needAlphaTesting()) {
  52062. var alphaTexture = material.getAlphaTestTexture();
  52063. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  52064. if (alphaTexture) {
  52065. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52066. }
  52067. }
  52068. // Bones
  52069. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52070. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52071. }
  52072. }
  52073. // Draw
  52074. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  52075. }
  52076. };
  52077. // Render target texture callbacks
  52078. var savedSceneClearColor;
  52079. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  52080. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  52081. savedSceneClearColor = scene.clearColor;
  52082. scene.clearColor = sceneClearColor;
  52083. });
  52084. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  52085. scene.clearColor = savedSceneClearColor;
  52086. });
  52087. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  52088. var engine = scene.getEngine();
  52089. var index;
  52090. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52091. renderSubMesh(opaqueSubMeshes.data[index]);
  52092. }
  52093. engine.setAlphaTesting(true);
  52094. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52095. renderSubMesh(alphaTestSubMeshes.data[index]);
  52096. }
  52097. engine.setAlphaTesting(false);
  52098. if (transparentSubMeshes.length) {
  52099. // Sort sub meshes
  52100. for (index = 0; index < transparentSubMeshes.length; index++) {
  52101. var submesh = transparentSubMeshes.data[index];
  52102. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  52103. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  52104. }
  52105. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  52106. sortedArray.sort(function (a, b) {
  52107. // Alpha index first
  52108. if (a._alphaIndex > b._alphaIndex) {
  52109. return 1;
  52110. }
  52111. if (a._alphaIndex < b._alphaIndex) {
  52112. return -1;
  52113. }
  52114. // Then distance to camera
  52115. if (a._distanceToCamera < b._distanceToCamera) {
  52116. return 1;
  52117. }
  52118. if (a._distanceToCamera > b._distanceToCamera) {
  52119. return -1;
  52120. }
  52121. return 0;
  52122. });
  52123. // Render sub meshes
  52124. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52125. for (index = 0; index < sortedArray.length; index++) {
  52126. renderSubMesh(sortedArray[index]);
  52127. }
  52128. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52129. }
  52130. };
  52131. };
  52132. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  52133. var transform = scene.getTransformMatrix();
  52134. var meshPosition;
  52135. if (this.useCustomMeshPosition) {
  52136. meshPosition = this.customMeshPosition;
  52137. }
  52138. else if (this.attachedNode) {
  52139. meshPosition = this.attachedNode.position;
  52140. }
  52141. else {
  52142. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  52143. }
  52144. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  52145. this._screenCoordinates.x = pos.x / this._viewPort.width;
  52146. this._screenCoordinates.y = pos.y / this._viewPort.height;
  52147. if (this.invert)
  52148. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  52149. };
  52150. // Static methods
  52151. /**
  52152. * Creates a default mesh for the Volumeric Light Scattering post-process
  52153. * @param {string} The mesh name
  52154. * @param {BABYLON.Scene} The scene where to create the mesh
  52155. * @return {BABYLON.Mesh} the default mesh
  52156. */
  52157. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  52158. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  52159. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  52160. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  52161. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  52162. mesh.material = material;
  52163. return mesh;
  52164. };
  52165. return VolumetricLightScatteringPostProcess;
  52166. }(BABYLON.PostProcess));
  52167. __decorate([
  52168. BABYLON.serializeAsVector3()
  52169. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  52170. __decorate([
  52171. BABYLON.serialize()
  52172. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  52173. __decorate([
  52174. BABYLON.serialize()
  52175. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  52176. __decorate([
  52177. BABYLON.serializeAsMeshReference()
  52178. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  52179. __decorate([
  52180. BABYLON.serialize()
  52181. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  52182. __decorate([
  52183. BABYLON.serialize()
  52184. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  52185. __decorate([
  52186. BABYLON.serialize()
  52187. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  52188. __decorate([
  52189. BABYLON.serialize()
  52190. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  52191. __decorate([
  52192. BABYLON.serialize()
  52193. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  52194. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  52195. })(BABYLON || (BABYLON = {}));
  52196. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  52197. //
  52198. // This post-process allows the modification of rendered colors by using
  52199. // a 'look-up table' (LUT). This effect is also called Color Grading.
  52200. //
  52201. // The object needs to be provided an url to a texture containing the color
  52202. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  52203. // Use an image editing software to tweak the LUT to match your needs.
  52204. //
  52205. // For an example of a color LUT, see here:
  52206. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  52207. // For explanations on color grading, see here:
  52208. // http://udn.epicgames.com/Three/ColorGrading.html
  52209. //
  52210. var BABYLON;
  52211. (function (BABYLON) {
  52212. var ColorCorrectionPostProcess = (function (_super) {
  52213. __extends(ColorCorrectionPostProcess, _super);
  52214. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  52215. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  52216. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52217. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  52218. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52219. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52220. _this.onApply = function (effect) {
  52221. effect.setTexture("colorTable", _this._colorTableTexture);
  52222. };
  52223. return _this;
  52224. }
  52225. return ColorCorrectionPostProcess;
  52226. }(BABYLON.PostProcess));
  52227. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  52228. })(BABYLON || (BABYLON = {}));
  52229. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  52230. var BABYLON;
  52231. (function (BABYLON) {
  52232. var TonemappingOperator;
  52233. (function (TonemappingOperator) {
  52234. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  52235. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  52236. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  52237. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  52238. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  52239. ;
  52240. var TonemapPostProcess = (function (_super) {
  52241. __extends(TonemapPostProcess, _super);
  52242. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  52243. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52244. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52245. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  52246. _this._operator = _operator;
  52247. _this.exposureAdjustment = exposureAdjustment;
  52248. var defines = "#define ";
  52249. if (_this._operator === TonemappingOperator.Hable)
  52250. defines += "HABLE_TONEMAPPING";
  52251. else if (_this._operator === TonemappingOperator.Reinhard)
  52252. defines += "REINHARD_TONEMAPPING";
  52253. else if (_this._operator === TonemappingOperator.HejiDawson)
  52254. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  52255. else if (_this._operator === TonemappingOperator.Photographic)
  52256. defines += "PHOTOGRAPHIC_TONEMAPPING";
  52257. //sadly a second call to create the effect.
  52258. _this.updateEffect(defines);
  52259. _this.onApply = function (effect) {
  52260. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  52261. };
  52262. return _this;
  52263. }
  52264. return TonemapPostProcess;
  52265. }(BABYLON.PostProcess));
  52266. BABYLON.TonemapPostProcess = TonemapPostProcess;
  52267. })(BABYLON || (BABYLON = {}));
  52268. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  52269. var BABYLON;
  52270. (function (BABYLON) {
  52271. var DisplayPassPostProcess = (function (_super) {
  52272. __extends(DisplayPassPostProcess, _super);
  52273. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  52274. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  52275. }
  52276. return DisplayPassPostProcess;
  52277. }(BABYLON.PostProcess));
  52278. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  52279. })(BABYLON || (BABYLON = {}));
  52280. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  52281. var BABYLON;
  52282. (function (BABYLON) {
  52283. var HighlightsPostProcess = (function (_super) {
  52284. __extends(HighlightsPostProcess, _super);
  52285. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  52286. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52287. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  52288. }
  52289. return HighlightsPostProcess;
  52290. }(BABYLON.PostProcess));
  52291. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  52292. })(BABYLON || (BABYLON = {}));
  52293. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  52294. var BABYLON;
  52295. (function (BABYLON) {
  52296. var ImageProcessingPostProcess = (function (_super) {
  52297. __extends(ImageProcessingPostProcess, _super);
  52298. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  52299. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52300. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  52301. _this._fromLinearSpace = true;
  52302. /**
  52303. * Defines cache preventing GC.
  52304. */
  52305. _this._defines = {
  52306. IMAGEPROCESSING: false,
  52307. VIGNETTE: false,
  52308. VIGNETTEBLENDMODEMULTIPLY: false,
  52309. VIGNETTEBLENDMODEOPAQUE: false,
  52310. TONEMAPPING: false,
  52311. CONTRAST: false,
  52312. COLORCURVES: false,
  52313. COLORGRADING: false,
  52314. FROMLINEARSPACE: false,
  52315. SAMPLER3DGREENDEPTH: false,
  52316. SAMPLER3DBGRMAP: false,
  52317. IMAGEPROCESSINGPOSTPROCESS: false,
  52318. EXPOSURE: false,
  52319. };
  52320. // Setup the default processing configuration to the scene.
  52321. _this._attachImageProcessingConfiguration(null);
  52322. _this.imageProcessingConfiguration.applyByPostProcess = true;
  52323. _this._updateParameters();
  52324. _this.onApply = function (effect) {
  52325. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  52326. };
  52327. return _this;
  52328. }
  52329. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  52330. /**
  52331. * Gets the image processing configuration used either in this material.
  52332. */
  52333. get: function () {
  52334. return this._imageProcessingConfiguration;
  52335. },
  52336. /**
  52337. * Sets the Default image processing configuration used either in the this material.
  52338. *
  52339. * If sets to null, the scene one is in use.
  52340. */
  52341. set: function (value) {
  52342. this._attachImageProcessingConfiguration(value);
  52343. },
  52344. enumerable: true,
  52345. configurable: true
  52346. });
  52347. /**
  52348. * Attaches a new image processing configuration to the PBR Material.
  52349. * @param configuration
  52350. */
  52351. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration) {
  52352. var _this = this;
  52353. if (configuration === this._imageProcessingConfiguration) {
  52354. return;
  52355. }
  52356. // Detaches observer.
  52357. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  52358. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  52359. }
  52360. // Pick the scene configuration if needed.
  52361. if (!configuration) {
  52362. var camera = this.getCamera();
  52363. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  52364. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  52365. }
  52366. else {
  52367. this._imageProcessingConfiguration = configuration;
  52368. }
  52369. // Attaches observer.
  52370. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  52371. _this._updateParameters();
  52372. });
  52373. // Ensure the effect will be rebuilt.
  52374. this._updateParameters();
  52375. };
  52376. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  52377. /**
  52378. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  52379. */
  52380. get: function () {
  52381. return this.imageProcessingConfiguration.colorCurves;
  52382. },
  52383. /**
  52384. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  52385. */
  52386. set: function (value) {
  52387. this.imageProcessingConfiguration.colorCurves = value;
  52388. },
  52389. enumerable: true,
  52390. configurable: true
  52391. });
  52392. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  52393. /**
  52394. * Gets wether the color curves effect is enabled.
  52395. */
  52396. get: function () {
  52397. return this.imageProcessingConfiguration.colorCurvesEnabled;
  52398. },
  52399. /**
  52400. * Sets wether the color curves effect is enabled.
  52401. */
  52402. set: function (value) {
  52403. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  52404. },
  52405. enumerable: true,
  52406. configurable: true
  52407. });
  52408. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  52409. /**
  52410. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  52411. */
  52412. get: function () {
  52413. return this.imageProcessingConfiguration.colorGradingTexture;
  52414. },
  52415. /**
  52416. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  52417. */
  52418. set: function (value) {
  52419. this.imageProcessingConfiguration.colorGradingTexture = value;
  52420. },
  52421. enumerable: true,
  52422. configurable: true
  52423. });
  52424. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  52425. /**
  52426. * Gets wether the color grading effect is enabled.
  52427. */
  52428. get: function () {
  52429. return this.imageProcessingConfiguration.colorGradingEnabled;
  52430. },
  52431. /**
  52432. * Gets wether the color grading effect is enabled.
  52433. */
  52434. set: function (value) {
  52435. this.imageProcessingConfiguration.colorGradingEnabled = value;
  52436. },
  52437. enumerable: true,
  52438. configurable: true
  52439. });
  52440. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  52441. /**
  52442. * Gets exposure used in the effect.
  52443. */
  52444. get: function () {
  52445. return this.imageProcessingConfiguration.exposure;
  52446. },
  52447. /**
  52448. * Sets exposure used in the effect.
  52449. */
  52450. set: function (value) {
  52451. this.imageProcessingConfiguration.exposure = value;
  52452. },
  52453. enumerable: true,
  52454. configurable: true
  52455. });
  52456. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  52457. /**
  52458. * Gets wether tonemapping is enabled or not.
  52459. */
  52460. get: function () {
  52461. return this._imageProcessingConfiguration.toneMappingEnabled;
  52462. },
  52463. /**
  52464. * Sets wether tonemapping is enabled or not
  52465. */
  52466. set: function (value) {
  52467. this._imageProcessingConfiguration.toneMappingEnabled = value;
  52468. },
  52469. enumerable: true,
  52470. configurable: true
  52471. });
  52472. ;
  52473. ;
  52474. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  52475. /**
  52476. * Gets contrast used in the effect.
  52477. */
  52478. get: function () {
  52479. return this.imageProcessingConfiguration.contrast;
  52480. },
  52481. /**
  52482. * Sets contrast used in the effect.
  52483. */
  52484. set: function (value) {
  52485. this.imageProcessingConfiguration.contrast = value;
  52486. },
  52487. enumerable: true,
  52488. configurable: true
  52489. });
  52490. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  52491. /**
  52492. * Gets Vignette stretch size.
  52493. */
  52494. get: function () {
  52495. return this.imageProcessingConfiguration.vignetteStretch;
  52496. },
  52497. /**
  52498. * Sets Vignette stretch size.
  52499. */
  52500. set: function (value) {
  52501. this.imageProcessingConfiguration.vignetteStretch = value;
  52502. },
  52503. enumerable: true,
  52504. configurable: true
  52505. });
  52506. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  52507. /**
  52508. * Gets Vignette centre X Offset.
  52509. */
  52510. get: function () {
  52511. return this.imageProcessingConfiguration.vignetteCentreX;
  52512. },
  52513. /**
  52514. * Sets Vignette centre X Offset.
  52515. */
  52516. set: function (value) {
  52517. this.imageProcessingConfiguration.vignetteCentreX = value;
  52518. },
  52519. enumerable: true,
  52520. configurable: true
  52521. });
  52522. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  52523. /**
  52524. * Gets Vignette centre Y Offset.
  52525. */
  52526. get: function () {
  52527. return this.imageProcessingConfiguration.vignetteCentreY;
  52528. },
  52529. /**
  52530. * Sets Vignette centre Y Offset.
  52531. */
  52532. set: function (value) {
  52533. this.imageProcessingConfiguration.vignetteCentreY = value;
  52534. },
  52535. enumerable: true,
  52536. configurable: true
  52537. });
  52538. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  52539. /**
  52540. * Gets Vignette weight or intensity of the vignette effect.
  52541. */
  52542. get: function () {
  52543. return this.imageProcessingConfiguration.vignetteWeight;
  52544. },
  52545. /**
  52546. * Sets Vignette weight or intensity of the vignette effect.
  52547. */
  52548. set: function (value) {
  52549. this.imageProcessingConfiguration.vignetteWeight = value;
  52550. },
  52551. enumerable: true,
  52552. configurable: true
  52553. });
  52554. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  52555. /**
  52556. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  52557. * if vignetteEnabled is set to true.
  52558. */
  52559. get: function () {
  52560. return this.imageProcessingConfiguration.vignetteColor;
  52561. },
  52562. /**
  52563. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  52564. * if vignetteEnabled is set to true.
  52565. */
  52566. set: function (value) {
  52567. this.imageProcessingConfiguration.vignetteColor = value;
  52568. },
  52569. enumerable: true,
  52570. configurable: true
  52571. });
  52572. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  52573. /**
  52574. * Gets Camera field of view used by the Vignette effect.
  52575. */
  52576. get: function () {
  52577. return this.imageProcessingConfiguration.vignetteCameraFov;
  52578. },
  52579. /**
  52580. * Sets Camera field of view used by the Vignette effect.
  52581. */
  52582. set: function (value) {
  52583. this.imageProcessingConfiguration.vignetteCameraFov = value;
  52584. },
  52585. enumerable: true,
  52586. configurable: true
  52587. });
  52588. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  52589. /**
  52590. * Gets the vignette blend mode allowing different kind of effect.
  52591. */
  52592. get: function () {
  52593. return this.imageProcessingConfiguration.vignetteBlendMode;
  52594. },
  52595. /**
  52596. * Sets the vignette blend mode allowing different kind of effect.
  52597. */
  52598. set: function (value) {
  52599. this.imageProcessingConfiguration.vignetteBlendMode = value;
  52600. },
  52601. enumerable: true,
  52602. configurable: true
  52603. });
  52604. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  52605. /**
  52606. * Gets wether the vignette effect is enabled.
  52607. */
  52608. get: function () {
  52609. return this.imageProcessingConfiguration.vignetteEnabled;
  52610. },
  52611. /**
  52612. * Sets wether the vignette effect is enabled.
  52613. */
  52614. set: function (value) {
  52615. this.imageProcessingConfiguration.vignetteEnabled = value;
  52616. },
  52617. enumerable: true,
  52618. configurable: true
  52619. });
  52620. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  52621. /**
  52622. * Gets wether the input of the processing is in Gamma or Linear Space.
  52623. */
  52624. get: function () {
  52625. return this._fromLinearSpace;
  52626. },
  52627. /**
  52628. * Sets wether the input of the processing is in Gamma or Linear Space.
  52629. */
  52630. set: function (value) {
  52631. if (this._fromLinearSpace === value) {
  52632. return;
  52633. }
  52634. this._fromLinearSpace = value;
  52635. this._updateParameters();
  52636. },
  52637. enumerable: true,
  52638. configurable: true
  52639. });
  52640. ImageProcessingPostProcess.prototype._updateParameters = function () {
  52641. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  52642. this.imageProcessingConfiguration.prepareDefines(this._defines);
  52643. var defines = "";
  52644. for (var define in this._defines) {
  52645. if (this._defines[define]) {
  52646. defines += "#define " + define + ";\r\n";
  52647. }
  52648. }
  52649. var samplers = ["textureSampler"];
  52650. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  52651. var uniforms = ["scale"];
  52652. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  52653. this.updateEffect(defines, uniforms, samplers);
  52654. };
  52655. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  52656. _super.prototype.dispose.call(this, camera);
  52657. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  52658. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  52659. }
  52660. this.imageProcessingConfiguration.applyByPostProcess = false;
  52661. };
  52662. return ImageProcessingPostProcess;
  52663. }(BABYLON.PostProcess));
  52664. __decorate([
  52665. BABYLON.serialize()
  52666. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  52667. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  52668. })(BABYLON || (BABYLON = {}));
  52669. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  52670. var BABYLON;
  52671. (function (BABYLON) {
  52672. var BlurPostProcess = (function (_super) {
  52673. __extends(BlurPostProcess, _super);
  52674. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  52675. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52676. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52677. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  52678. _this.direction = direction;
  52679. _this._packedFloat = false;
  52680. _this.onApplyObservable.add(function (effect) {
  52681. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  52682. });
  52683. _this.kernel = kernel;
  52684. return _this;
  52685. }
  52686. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  52687. /**
  52688. * Gets the length in pixels of the blur sample region
  52689. */
  52690. get: function () {
  52691. return this._idealKernel;
  52692. },
  52693. /**
  52694. * Sets the length in pixels of the blur sample region
  52695. */
  52696. set: function (v) {
  52697. if (this._idealKernel === v) {
  52698. return;
  52699. }
  52700. v = Math.max(v, 1);
  52701. this._idealKernel = v;
  52702. this._kernel = this._nearestBestKernel(v);
  52703. this._updateParameters();
  52704. },
  52705. enumerable: true,
  52706. configurable: true
  52707. });
  52708. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  52709. /**
  52710. * Gets wether or not the blur is unpacking/repacking floats
  52711. */
  52712. get: function () {
  52713. return this._packedFloat;
  52714. },
  52715. /**
  52716. * Sets wether or not the blur needs to unpack/repack floats
  52717. */
  52718. set: function (v) {
  52719. if (this._packedFloat === v) {
  52720. return;
  52721. }
  52722. this._packedFloat = v;
  52723. this._updateParameters();
  52724. },
  52725. enumerable: true,
  52726. configurable: true
  52727. });
  52728. BlurPostProcess.prototype._updateParameters = function () {
  52729. // Generate sampling offsets and weights
  52730. var N = this._kernel;
  52731. var centerIndex = (N - 1) / 2;
  52732. // Generate Gaussian sampling weights over kernel
  52733. var offsets = [];
  52734. var weights = [];
  52735. var totalWeight = 0;
  52736. for (var i = 0; i < N; i++) {
  52737. var u = i / (N - 1);
  52738. var w = this._gaussianWeight(u * 2.0 - 1);
  52739. offsets[i] = (i - centerIndex);
  52740. weights[i] = w;
  52741. totalWeight += w;
  52742. }
  52743. // Normalize weights
  52744. for (var i = 0; i < weights.length; i++) {
  52745. weights[i] /= totalWeight;
  52746. }
  52747. // Optimize: combine samples to take advantage of hardware linear sampling
  52748. // Walk from left to center, combining pairs (symmetrically)
  52749. var linearSamplingWeights = [];
  52750. var linearSamplingOffsets = [];
  52751. var linearSamplingMap = [];
  52752. for (var i = 0; i <= centerIndex; i += 2) {
  52753. var j = Math.min(i + 1, Math.floor(centerIndex));
  52754. var singleCenterSample = i === j;
  52755. if (singleCenterSample) {
  52756. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  52757. }
  52758. else {
  52759. var sharedCell = j === centerIndex;
  52760. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  52761. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  52762. if (offsetLinear === 0) {
  52763. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  52764. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  52765. }
  52766. else {
  52767. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  52768. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  52769. }
  52770. }
  52771. }
  52772. for (var i = 0; i < linearSamplingMap.length; i++) {
  52773. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  52774. linearSamplingWeights[i] = linearSamplingMap[i].w;
  52775. }
  52776. // Replace with optimized
  52777. offsets = linearSamplingOffsets;
  52778. weights = linearSamplingWeights;
  52779. // Generate shaders
  52780. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  52781. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  52782. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  52783. var defines = "";
  52784. for (var i = 0; i < varyingCount; i++) {
  52785. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  52786. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  52787. }
  52788. var depCount = 0;
  52789. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  52790. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  52791. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  52792. depCount++;
  52793. }
  52794. if (this.packedFloat) {
  52795. defines += "#define PACKEDFLOAT 1";
  52796. }
  52797. this.updateEffect(defines, null, null, {
  52798. varyingCount: varyingCount,
  52799. depCount: depCount
  52800. });
  52801. };
  52802. /**
  52803. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  52804. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  52805. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  52806. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  52807. * The gaps between physical kernels are compensated for in the weighting of the samples
  52808. * @param idealKernel Ideal blur kernel.
  52809. * @return Nearest best kernel.
  52810. */
  52811. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  52812. var v = Math.round(idealKernel);
  52813. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  52814. var k = _a[_i];
  52815. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  52816. return Math.max(k, 3);
  52817. }
  52818. }
  52819. return Math.max(v, 3);
  52820. };
  52821. /**
  52822. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  52823. * @param x The point on the Gaussian distribution to sample.
  52824. * @return the value of the Gaussian function at x.
  52825. */
  52826. BlurPostProcess.prototype._gaussianWeight = function (x) {
  52827. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  52828. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  52829. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  52830. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  52831. // truncated at around 1.3% of peak strength.
  52832. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  52833. var sigma = (1 / 3);
  52834. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  52835. var exponent = -((x * x) / (2.0 * sigma * sigma));
  52836. var weight = (1.0 / denominator) * Math.exp(exponent);
  52837. return weight;
  52838. };
  52839. /**
  52840. * Generates a string that can be used as a floating point number in GLSL.
  52841. * @param x Value to print.
  52842. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  52843. * @return GLSL float string.
  52844. */
  52845. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  52846. if (decimalFigures === void 0) { decimalFigures = 8; }
  52847. return x.toFixed(decimalFigures).replace(/0+$/, '');
  52848. };
  52849. return BlurPostProcess;
  52850. }(BABYLON.PostProcess));
  52851. BABYLON.BlurPostProcess = BlurPostProcess;
  52852. })(BABYLON || (BABYLON = {}));
  52853. //# sourceMappingURL=babylon.blurPostProcess.js.map
  52854. /// <reference path="..\babylon.node.ts" />
  52855. var BABYLON;
  52856. (function (BABYLON) {
  52857. var Bone = (function (_super) {
  52858. __extends(Bone, _super);
  52859. function Bone(name, skeleton, parentBone, matrix, restPose) {
  52860. if (parentBone === void 0) { parentBone = null; }
  52861. var _this = _super.call(this, name, skeleton.getScene()) || this;
  52862. _this.name = name;
  52863. _this.children = new Array();
  52864. _this.animations = new Array();
  52865. _this._worldTransform = new BABYLON.Matrix();
  52866. _this._absoluteTransform = new BABYLON.Matrix();
  52867. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  52868. _this._scaleMatrix = BABYLON.Matrix.Identity();
  52869. _this._scaleVector = BABYLON.Vector3.One();
  52870. _this._negateScaleChildren = BABYLON.Vector3.One();
  52871. _this._scalingDeterminant = 1;
  52872. _this._skeleton = skeleton;
  52873. _this._localMatrix = matrix ? matrix : BABYLON.Matrix.Identity();
  52874. _this._baseMatrix = _this._localMatrix.clone();
  52875. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  52876. skeleton.bones.push(_this);
  52877. _this.setParent(parentBone, false);
  52878. _this._updateDifferenceMatrix();
  52879. return _this;
  52880. }
  52881. Object.defineProperty(Bone.prototype, "_matrix", {
  52882. get: function () {
  52883. return this._localMatrix;
  52884. },
  52885. set: function (val) {
  52886. if (this._localMatrix) {
  52887. this._localMatrix.copyFrom(val);
  52888. }
  52889. else {
  52890. this._localMatrix = val;
  52891. }
  52892. },
  52893. enumerable: true,
  52894. configurable: true
  52895. });
  52896. // Members
  52897. Bone.prototype.getSkeleton = function () {
  52898. return this._skeleton;
  52899. };
  52900. Bone.prototype.getParent = function () {
  52901. return this._parent;
  52902. };
  52903. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  52904. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  52905. if (this._parent === parent) {
  52906. return;
  52907. }
  52908. if (this._parent) {
  52909. var index = this._parent.children.indexOf(this);
  52910. if (index !== -1) {
  52911. this._parent.children.splice(index);
  52912. }
  52913. }
  52914. this._parent = parent;
  52915. if (this._parent) {
  52916. this._parent.children.push(this);
  52917. }
  52918. if (updateDifferenceMatrix) {
  52919. this._updateDifferenceMatrix();
  52920. }
  52921. };
  52922. Bone.prototype.getLocalMatrix = function () {
  52923. return this._localMatrix;
  52924. };
  52925. Bone.prototype.getBaseMatrix = function () {
  52926. return this._baseMatrix;
  52927. };
  52928. Bone.prototype.getRestPose = function () {
  52929. return this._restPose;
  52930. };
  52931. Bone.prototype.returnToRest = function () {
  52932. this.updateMatrix(this._restPose.clone());
  52933. };
  52934. Bone.prototype.getWorldMatrix = function () {
  52935. return this._worldTransform;
  52936. };
  52937. Bone.prototype.getInvertedAbsoluteTransform = function () {
  52938. return this._invertedAbsoluteTransform;
  52939. };
  52940. Bone.prototype.getAbsoluteTransform = function () {
  52941. return this._absoluteTransform;
  52942. };
  52943. Object.defineProperty(Bone.prototype, "position", {
  52944. // Properties (matches AbstractMesh properties)
  52945. get: function () {
  52946. return this.getPosition();
  52947. },
  52948. set: function (newPosition) {
  52949. this.setPosition(newPosition);
  52950. },
  52951. enumerable: true,
  52952. configurable: true
  52953. });
  52954. Object.defineProperty(Bone.prototype, "rotation", {
  52955. get: function () {
  52956. return this.getRotation();
  52957. },
  52958. set: function (newRotation) {
  52959. this.setRotation(newRotation);
  52960. },
  52961. enumerable: true,
  52962. configurable: true
  52963. });
  52964. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  52965. get: function () {
  52966. return this.getRotationQuaternion();
  52967. },
  52968. set: function (newRotation) {
  52969. this.setRotationQuaternion(newRotation);
  52970. },
  52971. enumerable: true,
  52972. configurable: true
  52973. });
  52974. Object.defineProperty(Bone.prototype, "scaling", {
  52975. get: function () {
  52976. return this.getScale();
  52977. },
  52978. set: function (newScaling) {
  52979. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  52980. },
  52981. enumerable: true,
  52982. configurable: true
  52983. });
  52984. // Methods
  52985. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  52986. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  52987. this._baseMatrix = matrix.clone();
  52988. this._localMatrix = matrix.clone();
  52989. this._skeleton._markAsDirty();
  52990. if (updateDifferenceMatrix) {
  52991. this._updateDifferenceMatrix();
  52992. }
  52993. };
  52994. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  52995. if (!rootMatrix) {
  52996. rootMatrix = this._baseMatrix;
  52997. }
  52998. if (this._parent) {
  52999. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  53000. }
  53001. else {
  53002. this._absoluteTransform.copyFrom(rootMatrix);
  53003. }
  53004. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  53005. for (var index = 0; index < this.children.length; index++) {
  53006. this.children[index]._updateDifferenceMatrix();
  53007. }
  53008. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  53009. };
  53010. Bone.prototype.markAsDirty = function () {
  53011. this._currentRenderId++;
  53012. this._skeleton._markAsDirty();
  53013. };
  53014. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  53015. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  53016. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  53017. // all animation may be coming from a library skeleton, so may need to create animation
  53018. if (this.animations.length === 0) {
  53019. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  53020. this.animations[0].setKeys([]);
  53021. }
  53022. // get animation info / verify there is such a range from the source bone
  53023. var sourceRange = source.animations[0].getRange(rangeName);
  53024. if (!sourceRange) {
  53025. return false;
  53026. }
  53027. var from = sourceRange.from;
  53028. var to = sourceRange.to;
  53029. var sourceKeys = source.animations[0].getKeys();
  53030. // rescaling prep
  53031. var sourceBoneLength = source.length;
  53032. var sourceParent = source.getParent();
  53033. var parent = this.getParent();
  53034. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  53035. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  53036. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  53037. var destKeys = this.animations[0].getKeys();
  53038. // loop vars declaration
  53039. var orig;
  53040. var origTranslation;
  53041. var mat;
  53042. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  53043. orig = sourceKeys[key];
  53044. if (orig.frame >= from && orig.frame <= to) {
  53045. if (rescaleAsRequired) {
  53046. mat = orig.value.clone();
  53047. // scale based on parent ratio, when bone has parent
  53048. if (parentScalingReqd) {
  53049. origTranslation = mat.getTranslation();
  53050. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  53051. // scale based on skeleton dimension ratio when root bone, and value is passed
  53052. }
  53053. else if (dimensionsScalingReqd) {
  53054. origTranslation = mat.getTranslation();
  53055. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  53056. // use original when root bone, and no data for skelDimensionsRatio
  53057. }
  53058. else {
  53059. mat = orig.value;
  53060. }
  53061. }
  53062. else {
  53063. mat = orig.value;
  53064. }
  53065. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  53066. }
  53067. }
  53068. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  53069. return true;
  53070. };
  53071. /**
  53072. * Translate the bone in local or world space.
  53073. * @param vec The amount to translate the bone.
  53074. * @param space The space that the translation is in.
  53075. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53076. */
  53077. Bone.prototype.translate = function (vec, space, mesh) {
  53078. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53079. var lm = this.getLocalMatrix();
  53080. if (space == BABYLON.Space.LOCAL) {
  53081. lm.m[12] += vec.x;
  53082. lm.m[13] += vec.y;
  53083. lm.m[14] += vec.z;
  53084. }
  53085. else {
  53086. var wm;
  53087. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53088. if (mesh) {
  53089. wm = mesh.getWorldMatrix();
  53090. }
  53091. this._skeleton.computeAbsoluteTransforms();
  53092. var tmat = Bone._tmpMats[0];
  53093. var tvec = Bone._tmpVecs[0];
  53094. if (mesh) {
  53095. tmat.copyFrom(this._parent.getAbsoluteTransform());
  53096. tmat.multiplyToRef(wm, tmat);
  53097. }
  53098. else {
  53099. tmat.copyFrom(this._parent.getAbsoluteTransform());
  53100. }
  53101. tmat.m[12] = 0;
  53102. tmat.m[13] = 0;
  53103. tmat.m[14] = 0;
  53104. tmat.invert();
  53105. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  53106. lm.m[12] += tvec.x;
  53107. lm.m[13] += tvec.y;
  53108. lm.m[14] += tvec.z;
  53109. }
  53110. this.markAsDirty();
  53111. };
  53112. /**
  53113. * Set the postion of the bone in local or world space.
  53114. * @param position The position to set the bone.
  53115. * @param space The space that the position is in.
  53116. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53117. */
  53118. Bone.prototype.setPosition = function (position, space, mesh) {
  53119. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53120. var lm = this.getLocalMatrix();
  53121. if (space == BABYLON.Space.LOCAL) {
  53122. lm.m[12] = position.x;
  53123. lm.m[13] = position.y;
  53124. lm.m[14] = position.z;
  53125. }
  53126. else {
  53127. var wm;
  53128. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53129. if (mesh) {
  53130. wm = mesh.getWorldMatrix();
  53131. }
  53132. this._skeleton.computeAbsoluteTransforms();
  53133. var tmat = Bone._tmpMats[0];
  53134. var vec = Bone._tmpVecs[0];
  53135. if (mesh) {
  53136. tmat.copyFrom(this._parent.getAbsoluteTransform());
  53137. tmat.multiplyToRef(wm, tmat);
  53138. }
  53139. else {
  53140. tmat.copyFrom(this._parent.getAbsoluteTransform());
  53141. }
  53142. tmat.invert();
  53143. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  53144. lm.m[12] = vec.x;
  53145. lm.m[13] = vec.y;
  53146. lm.m[14] = vec.z;
  53147. }
  53148. this.markAsDirty();
  53149. };
  53150. /**
  53151. * Set the absolute postion of the bone (world space).
  53152. * @param position The position to set the bone.
  53153. * @param mesh The mesh that this bone is attached to.
  53154. */
  53155. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  53156. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  53157. };
  53158. /**
  53159. * Set the scale of the bone on the x, y and z axes.
  53160. * @param x The scale of the bone on the x axis.
  53161. * @param x The scale of the bone on the y axis.
  53162. * @param z The scale of the bone on the z axis.
  53163. * @param scaleChildren Set this to true if children of the bone should be scaled.
  53164. */
  53165. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  53166. if (scaleChildren === void 0) { scaleChildren = false; }
  53167. if (this.animations[0] && !this.animations[0].isStopped()) {
  53168. if (!scaleChildren) {
  53169. this._negateScaleChildren.x = 1 / x;
  53170. this._negateScaleChildren.y = 1 / y;
  53171. this._negateScaleChildren.z = 1 / z;
  53172. }
  53173. this._syncScaleVector();
  53174. }
  53175. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  53176. };
  53177. /**
  53178. * Scale the bone on the x, y and z axes.
  53179. * @param x The amount to scale the bone on the x axis.
  53180. * @param x The amount to scale the bone on the y axis.
  53181. * @param z The amount to scale the bone on the z axis.
  53182. * @param scaleChildren Set this to true if children of the bone should be scaled.
  53183. */
  53184. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  53185. if (scaleChildren === void 0) { scaleChildren = false; }
  53186. var locMat = this.getLocalMatrix();
  53187. var origLocMat = Bone._tmpMats[0];
  53188. origLocMat.copyFrom(locMat);
  53189. var origLocMatInv = Bone._tmpMats[1];
  53190. origLocMatInv.copyFrom(origLocMat);
  53191. origLocMatInv.invert();
  53192. var scaleMat = Bone._tmpMats[2];
  53193. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  53194. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  53195. this._scaleVector.x *= x;
  53196. this._scaleVector.y *= y;
  53197. this._scaleVector.z *= z;
  53198. locMat.multiplyToRef(origLocMatInv, locMat);
  53199. locMat.multiplyToRef(scaleMat, locMat);
  53200. locMat.multiplyToRef(origLocMat, locMat);
  53201. var parent = this.getParent();
  53202. if (parent) {
  53203. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  53204. }
  53205. else {
  53206. this.getAbsoluteTransform().copyFrom(locMat);
  53207. }
  53208. var len = this.children.length;
  53209. scaleMat.invert();
  53210. for (var i = 0; i < len; i++) {
  53211. var child = this.children[i];
  53212. var cm = child.getLocalMatrix();
  53213. cm.multiplyToRef(scaleMat, cm);
  53214. var lm = child.getLocalMatrix();
  53215. lm.m[12] *= x;
  53216. lm.m[13] *= y;
  53217. lm.m[14] *= z;
  53218. }
  53219. this.computeAbsoluteTransforms();
  53220. if (scaleChildren) {
  53221. for (var i = 0; i < len; i++) {
  53222. this.children[i].scale(x, y, z, scaleChildren);
  53223. }
  53224. }
  53225. this.markAsDirty();
  53226. };
  53227. /**
  53228. * Set the yaw, pitch, and roll of the bone in local or world space.
  53229. * @param yaw The rotation of the bone on the y axis.
  53230. * @param pitch The rotation of the bone on the x axis.
  53231. * @param roll The rotation of the bone on the z axis.
  53232. * @param space The space that the axes of rotation are in.
  53233. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53234. */
  53235. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  53236. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53237. var rotMat = Bone._tmpMats[0];
  53238. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  53239. var rotMatInv = Bone._tmpMats[1];
  53240. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  53241. rotMatInv.multiplyToRef(rotMat, rotMat);
  53242. this._rotateWithMatrix(rotMat, space, mesh);
  53243. };
  53244. /**
  53245. * Rotate the bone on an axis in local or world space.
  53246. * @param axis The axis to rotate the bone on.
  53247. * @param amount The amount to rotate the bone.
  53248. * @param space The space that the axis is in.
  53249. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53250. */
  53251. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  53252. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53253. var rmat = Bone._tmpMats[0];
  53254. rmat.m[12] = 0;
  53255. rmat.m[13] = 0;
  53256. rmat.m[14] = 0;
  53257. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  53258. this._rotateWithMatrix(rmat, space, mesh);
  53259. };
  53260. /**
  53261. * Set the rotation of the bone to a particular axis angle in local or world space.
  53262. * @param axis The axis to rotate the bone on.
  53263. * @param angle The angle that the bone should be rotated to.
  53264. * @param space The space that the axis is in.
  53265. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53266. */
  53267. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  53268. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53269. var rotMat = Bone._tmpMats[0];
  53270. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  53271. var rotMatInv = Bone._tmpMats[1];
  53272. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  53273. rotMatInv.multiplyToRef(rotMat, rotMat);
  53274. this._rotateWithMatrix(rotMat, space, mesh);
  53275. };
  53276. /**
  53277. * Set the euler rotation of the bone in local of world space.
  53278. * @param rotation The euler rotation that the bone should be set to.
  53279. * @param space The space that the rotation is in.
  53280. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53281. */
  53282. Bone.prototype.setRotation = function (rotation, space, mesh) {
  53283. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53284. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  53285. };
  53286. /**
  53287. * Set the quaternion rotation of the bone in local of world space.
  53288. * @param quat The quaternion rotation that the bone should be set to.
  53289. * @param space The space that the rotation is in.
  53290. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53291. */
  53292. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  53293. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53294. var rotMatInv = Bone._tmpMats[0];
  53295. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  53296. var rotMat = Bone._tmpMats[1];
  53297. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  53298. rotMatInv.multiplyToRef(rotMat, rotMat);
  53299. this._rotateWithMatrix(rotMat, space, mesh);
  53300. };
  53301. /**
  53302. * Set the rotation matrix of the bone in local of world space.
  53303. * @param rotMat The rotation matrix that the bone should be set to.
  53304. * @param space The space that the rotation is in.
  53305. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53306. */
  53307. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  53308. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53309. var rotMatInv = Bone._tmpMats[0];
  53310. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  53311. var rotMat2 = Bone._tmpMats[1];
  53312. rotMat2.copyFrom(rotMat);
  53313. rotMatInv.multiplyToRef(rotMat, rotMat2);
  53314. this._rotateWithMatrix(rotMat2, space, mesh);
  53315. };
  53316. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  53317. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53318. var lmat = this.getLocalMatrix();
  53319. var lx = lmat.m[12];
  53320. var ly = lmat.m[13];
  53321. var lz = lmat.m[14];
  53322. var parent = this.getParent();
  53323. var parentScale = Bone._tmpMats[3];
  53324. var parentScaleInv = Bone._tmpMats[4];
  53325. if (parent) {
  53326. if (space == BABYLON.Space.WORLD) {
  53327. if (mesh) {
  53328. parentScale.copyFrom(mesh.getWorldMatrix());
  53329. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  53330. }
  53331. else {
  53332. parentScale.copyFrom(parent.getAbsoluteTransform());
  53333. }
  53334. }
  53335. else {
  53336. parentScale = parent._scaleMatrix;
  53337. }
  53338. parentScaleInv.copyFrom(parentScale);
  53339. parentScaleInv.invert();
  53340. lmat.multiplyToRef(parentScale, lmat);
  53341. lmat.multiplyToRef(rmat, lmat);
  53342. lmat.multiplyToRef(parentScaleInv, lmat);
  53343. }
  53344. else {
  53345. if (space == BABYLON.Space.WORLD && mesh) {
  53346. parentScale.copyFrom(mesh.getWorldMatrix());
  53347. parentScaleInv.copyFrom(parentScale);
  53348. parentScaleInv.invert();
  53349. lmat.multiplyToRef(parentScale, lmat);
  53350. lmat.multiplyToRef(rmat, lmat);
  53351. lmat.multiplyToRef(parentScaleInv, lmat);
  53352. }
  53353. else {
  53354. lmat.multiplyToRef(rmat, lmat);
  53355. }
  53356. }
  53357. lmat.m[12] = lx;
  53358. lmat.m[13] = ly;
  53359. lmat.m[14] = lz;
  53360. this.computeAbsoluteTransforms();
  53361. this.markAsDirty();
  53362. };
  53363. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  53364. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53365. if (space == BABYLON.Space.WORLD) {
  53366. var scaleMatrix = Bone._tmpMats[2];
  53367. scaleMatrix.copyFrom(this._scaleMatrix);
  53368. rotMatInv.copyFrom(this.getAbsoluteTransform());
  53369. if (mesh) {
  53370. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  53371. var meshScale = Bone._tmpMats[3];
  53372. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  53373. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  53374. }
  53375. rotMatInv.invert();
  53376. scaleMatrix.m[0] *= this._scalingDeterminant;
  53377. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  53378. }
  53379. else {
  53380. rotMatInv.copyFrom(this.getLocalMatrix());
  53381. rotMatInv.invert();
  53382. var scaleMatrix = Bone._tmpMats[2];
  53383. scaleMatrix.copyFrom(this._scaleMatrix);
  53384. if (this._parent) {
  53385. var pscaleMatrix = Bone._tmpMats[3];
  53386. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  53387. pscaleMatrix.invert();
  53388. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  53389. }
  53390. else {
  53391. scaleMatrix.m[0] *= this._scalingDeterminant;
  53392. }
  53393. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  53394. }
  53395. };
  53396. /**
  53397. * Get the scale of the bone
  53398. * @returns the scale of the bone
  53399. */
  53400. Bone.prototype.getScale = function () {
  53401. return this._scaleVector.clone();
  53402. };
  53403. /**
  53404. * Copy the scale of the bone to a vector3.
  53405. * @param result The vector3 to copy the scale to
  53406. */
  53407. Bone.prototype.getScaleToRef = function (result) {
  53408. result.copyFrom(this._scaleVector);
  53409. };
  53410. /**
  53411. * Get the position of the bone in local or world space.
  53412. * @param space The space that the returned position is in.
  53413. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53414. * @returns The position of the bone
  53415. */
  53416. Bone.prototype.getPosition = function (space, mesh) {
  53417. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53418. var pos = BABYLON.Vector3.Zero();
  53419. this.getPositionToRef(space, mesh, pos);
  53420. return pos;
  53421. };
  53422. /**
  53423. * Copy the position of the bone to a vector3 in local or world space.
  53424. * @param space The space that the returned position is in.
  53425. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53426. * @param result The vector3 to copy the position to.
  53427. */
  53428. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  53429. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53430. if (space == BABYLON.Space.LOCAL) {
  53431. var lm = this.getLocalMatrix();
  53432. result.x = lm.m[12];
  53433. result.y = lm.m[13];
  53434. result.z = lm.m[14];
  53435. }
  53436. else {
  53437. var wm;
  53438. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53439. if (mesh) {
  53440. wm = mesh.getWorldMatrix();
  53441. }
  53442. this._skeleton.computeAbsoluteTransforms();
  53443. var tmat = Bone._tmpMats[0];
  53444. if (mesh) {
  53445. tmat.copyFrom(this.getAbsoluteTransform());
  53446. tmat.multiplyToRef(wm, tmat);
  53447. }
  53448. else {
  53449. tmat = this.getAbsoluteTransform();
  53450. }
  53451. result.x = tmat.m[12];
  53452. result.y = tmat.m[13];
  53453. result.z = tmat.m[14];
  53454. }
  53455. };
  53456. /**
  53457. * Get the absolute position of the bone (world space).
  53458. * @param mesh The mesh that this bone is attached to.
  53459. * @returns The absolute position of the bone
  53460. */
  53461. Bone.prototype.getAbsolutePosition = function (mesh) {
  53462. var pos = BABYLON.Vector3.Zero();
  53463. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  53464. return pos;
  53465. };
  53466. /**
  53467. * Copy the absolute position of the bone (world space) to the result param.
  53468. * @param mesh The mesh that this bone is attached to.
  53469. * @param result The vector3 to copy the absolute position to.
  53470. */
  53471. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  53472. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  53473. };
  53474. /**
  53475. * Compute the absolute transforms of this bone and its children.
  53476. */
  53477. Bone.prototype.computeAbsoluteTransforms = function () {
  53478. if (this._parent) {
  53479. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  53480. }
  53481. else {
  53482. this._absoluteTransform.copyFrom(this._localMatrix);
  53483. var poseMatrix = this._skeleton.getPoseMatrix();
  53484. if (poseMatrix) {
  53485. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  53486. }
  53487. }
  53488. var children = this.children;
  53489. var len = children.length;
  53490. for (var i = 0; i < len; i++) {
  53491. children[i].computeAbsoluteTransforms();
  53492. }
  53493. };
  53494. Bone.prototype._syncScaleVector = function () {
  53495. var lm = this.getLocalMatrix();
  53496. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  53497. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  53498. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  53499. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  53500. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  53501. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  53502. this._scaleVector.x = xs * Math.sqrt(xsq);
  53503. this._scaleVector.y = ys * Math.sqrt(ysq);
  53504. this._scaleVector.z = zs * Math.sqrt(zsq);
  53505. if (this._parent) {
  53506. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  53507. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  53508. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  53509. }
  53510. 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);
  53511. };
  53512. /**
  53513. * Get the world direction from an axis that is in the local space of the bone.
  53514. * @param localAxis The local direction that is used to compute the world direction.
  53515. * @param mesh The mesh that this bone is attached to.
  53516. * @returns The world direction
  53517. */
  53518. Bone.prototype.getDirection = function (localAxis, mesh) {
  53519. var result = BABYLON.Vector3.Zero();
  53520. this.getDirectionToRef(localAxis, mesh, result);
  53521. return result;
  53522. };
  53523. /**
  53524. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  53525. * @param localAxis The local direction that is used to compute the world direction.
  53526. * @param mesh The mesh that this bone is attached to.
  53527. * @param result The vector3 that the world direction will be copied to.
  53528. */
  53529. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  53530. var wm;
  53531. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53532. if (mesh) {
  53533. wm = mesh.getWorldMatrix();
  53534. }
  53535. this._skeleton.computeAbsoluteTransforms();
  53536. var mat = Bone._tmpMats[0];
  53537. mat.copyFrom(this.getAbsoluteTransform());
  53538. if (mesh) {
  53539. mat.multiplyToRef(wm, mat);
  53540. }
  53541. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  53542. result.normalize();
  53543. };
  53544. /**
  53545. * Get the euler rotation of the bone in local or world space.
  53546. * @param space The space that the rotation should be in.
  53547. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53548. * @returns The euler rotation
  53549. */
  53550. Bone.prototype.getRotation = function (space, mesh) {
  53551. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53552. var result = BABYLON.Vector3.Zero();
  53553. this.getRotationToRef(space, mesh, result);
  53554. return result;
  53555. };
  53556. /**
  53557. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  53558. * @param space The space that the rotation should be in.
  53559. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53560. * @param result The vector3 that the rotation should be copied to.
  53561. */
  53562. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  53563. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53564. var quat = Bone._tmpQuat;
  53565. this.getRotationQuaternionToRef(space, mesh, quat);
  53566. quat.toEulerAnglesToRef(result);
  53567. };
  53568. /**
  53569. * Get the quaternion rotation of the bone in either local or world space.
  53570. * @param space The space that the rotation should be in.
  53571. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53572. * @returns The quaternion rotation
  53573. */
  53574. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  53575. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53576. var result = BABYLON.Quaternion.Identity();
  53577. this.getRotationQuaternionToRef(space, mesh, result);
  53578. return result;
  53579. };
  53580. /**
  53581. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  53582. * @param space The space that the rotation should be in.
  53583. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53584. * @param result The quaternion that the rotation should be copied to.
  53585. */
  53586. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  53587. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53588. if (space == BABYLON.Space.LOCAL) {
  53589. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  53590. }
  53591. else {
  53592. var mat = Bone._tmpMats[0];
  53593. var amat = this.getAbsoluteTransform();
  53594. if (mesh) {
  53595. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  53596. }
  53597. else {
  53598. mat.copyFrom(amat);
  53599. }
  53600. mat.m[0] *= this._scalingDeterminant;
  53601. mat.m[1] *= this._scalingDeterminant;
  53602. mat.m[2] *= this._scalingDeterminant;
  53603. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  53604. }
  53605. };
  53606. /**
  53607. * Get the rotation matrix of the bone in local or world space.
  53608. * @param space The space that the rotation should be in.
  53609. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53610. * @returns The rotation matrix
  53611. */
  53612. Bone.prototype.getRotationMatrix = function (space, mesh) {
  53613. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53614. var result = BABYLON.Matrix.Identity();
  53615. this.getRotationMatrixToRef(space, mesh, result);
  53616. return result;
  53617. };
  53618. /**
  53619. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  53620. * @param space The space that the rotation should be in.
  53621. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  53622. * @param result The quaternion that the rotation should be copied to.
  53623. */
  53624. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  53625. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  53626. if (space == BABYLON.Space.LOCAL) {
  53627. this.getLocalMatrix().getRotationMatrixToRef(result);
  53628. }
  53629. else {
  53630. var mat = Bone._tmpMats[0];
  53631. var amat = this.getAbsoluteTransform();
  53632. if (mesh) {
  53633. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  53634. }
  53635. else {
  53636. mat.copyFrom(amat);
  53637. }
  53638. mat.m[0] *= this._scalingDeterminant;
  53639. mat.m[1] *= this._scalingDeterminant;
  53640. mat.m[2] *= this._scalingDeterminant;
  53641. mat.getRotationMatrixToRef(result);
  53642. }
  53643. };
  53644. /**
  53645. * Get the world position of a point that is in the local space of the bone.
  53646. * @param position The local position
  53647. * @param mesh The mesh that this bone is attached to.
  53648. * @returns The world position
  53649. */
  53650. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  53651. var result = BABYLON.Vector3.Zero();
  53652. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  53653. return result;
  53654. };
  53655. /**
  53656. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  53657. * @param position The local position
  53658. * @param mesh The mesh that this bone is attached to.
  53659. * @param result The vector3 that the world position should be copied to.
  53660. */
  53661. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  53662. var wm;
  53663. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53664. if (mesh) {
  53665. wm = mesh.getWorldMatrix();
  53666. }
  53667. this._skeleton.computeAbsoluteTransforms();
  53668. var tmat = Bone._tmpMats[0];
  53669. if (mesh) {
  53670. tmat.copyFrom(this.getAbsoluteTransform());
  53671. tmat.multiplyToRef(wm, tmat);
  53672. }
  53673. else {
  53674. tmat = this.getAbsoluteTransform();
  53675. }
  53676. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  53677. };
  53678. /**
  53679. * Get the local position of a point that is in world space.
  53680. * @param position The world position
  53681. * @param mesh The mesh that this bone is attached to.
  53682. * @returns The local position
  53683. */
  53684. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  53685. var result = BABYLON.Vector3.Zero();
  53686. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  53687. return result;
  53688. };
  53689. /**
  53690. * Get the local position of a point that is in world space and copy it to the result param.
  53691. * @param position The world position
  53692. * @param mesh The mesh that this bone is attached to.
  53693. * @param result The vector3 that the local position should be copied to.
  53694. */
  53695. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  53696. var wm;
  53697. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  53698. if (mesh) {
  53699. wm = mesh.getWorldMatrix();
  53700. }
  53701. this._skeleton.computeAbsoluteTransforms();
  53702. var tmat = Bone._tmpMats[0];
  53703. tmat.copyFrom(this.getAbsoluteTransform());
  53704. if (mesh) {
  53705. tmat.multiplyToRef(wm, tmat);
  53706. }
  53707. tmat.invert();
  53708. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  53709. };
  53710. return Bone;
  53711. }(BABYLON.Node));
  53712. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  53713. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  53714. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  53715. BABYLON.Bone = Bone;
  53716. })(BABYLON || (BABYLON = {}));
  53717. //# sourceMappingURL=babylon.bone.js.map
  53718. var BABYLON;
  53719. (function (BABYLON) {
  53720. var BoneIKController = (function () {
  53721. function BoneIKController(mesh, bone, options) {
  53722. this.targetPosition = BABYLON.Vector3.Zero();
  53723. this.poleTargetPosition = BABYLON.Vector3.Zero();
  53724. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  53725. this.poleAngle = 0;
  53726. this.slerpAmount = 1;
  53727. this._bone1Quat = BABYLON.Quaternion.Identity();
  53728. this._bone1Mat = BABYLON.Matrix.Identity();
  53729. this._bone2Ang = Math.PI;
  53730. this._maxAngle = Math.PI;
  53731. this._rightHandedSystem = false;
  53732. this._bendAxis = BABYLON.Vector3.Right();
  53733. this._slerping = false;
  53734. this._adjustRoll = 0;
  53735. this._bone2 = bone;
  53736. this._bone1 = bone.getParent();
  53737. this.mesh = mesh;
  53738. var bonePos = bone.getPosition();
  53739. if (bone.getAbsoluteTransform().determinant() > 0) {
  53740. this._rightHandedSystem = true;
  53741. this._bendAxis.x = 0;
  53742. this._bendAxis.y = 0;
  53743. this._bendAxis.z = -1;
  53744. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  53745. this._adjustRoll = Math.PI * .5;
  53746. this._bendAxis.z = 1;
  53747. }
  53748. }
  53749. if (this._bone1.length) {
  53750. var boneScale1 = this._bone1.getScale();
  53751. var boneScale2 = this._bone2.getScale();
  53752. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  53753. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  53754. }
  53755. else if (this._bone1.children[0]) {
  53756. mesh.computeWorldMatrix(true);
  53757. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  53758. var pos2 = this._bone2.getAbsolutePosition(mesh);
  53759. var pos3 = this._bone1.getAbsolutePosition(mesh);
  53760. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  53761. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  53762. }
  53763. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  53764. this.maxAngle = Math.PI;
  53765. if (options) {
  53766. if (options.targetMesh) {
  53767. this.targetMesh = options.targetMesh;
  53768. this.targetMesh.computeWorldMatrix(true);
  53769. }
  53770. if (options.poleTargetMesh) {
  53771. this.poleTargetMesh = options.poleTargetMesh;
  53772. this.poleTargetMesh.computeWorldMatrix(true);
  53773. }
  53774. else if (options.poleTargetBone) {
  53775. this.poleTargetBone = options.poleTargetBone;
  53776. }
  53777. else if (this._bone1.getParent()) {
  53778. this.poleTargetBone = this._bone1.getParent();
  53779. }
  53780. if (options.poleTargetLocalOffset) {
  53781. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  53782. }
  53783. if (options.poleAngle) {
  53784. this.poleAngle = options.poleAngle;
  53785. }
  53786. if (options.bendAxis) {
  53787. this._bendAxis.copyFrom(options.bendAxis);
  53788. }
  53789. if (options.maxAngle) {
  53790. this.maxAngle = options.maxAngle;
  53791. }
  53792. if (options.slerpAmount) {
  53793. this.slerpAmount = options.slerpAmount;
  53794. }
  53795. }
  53796. }
  53797. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  53798. get: function () {
  53799. return this._maxAngle;
  53800. },
  53801. set: function (value) {
  53802. this._setMaxAngle(value);
  53803. },
  53804. enumerable: true,
  53805. configurable: true
  53806. });
  53807. BoneIKController.prototype._setMaxAngle = function (ang) {
  53808. if (ang < 0) {
  53809. ang = 0;
  53810. }
  53811. if (ang > Math.PI || ang == undefined) {
  53812. ang = Math.PI;
  53813. }
  53814. this._maxAngle = ang;
  53815. var a = this._bone1Length;
  53816. var b = this._bone2Length;
  53817. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  53818. };
  53819. BoneIKController.prototype.update = function () {
  53820. var bone1 = this._bone1;
  53821. var target = this.targetPosition;
  53822. var poleTarget = this.poleTargetPosition;
  53823. var mat1 = BoneIKController._tmpMats[0];
  53824. var mat2 = BoneIKController._tmpMats[1];
  53825. if (this.targetMesh) {
  53826. target.copyFrom(this.targetMesh.getAbsolutePosition());
  53827. }
  53828. if (this.poleTargetBone) {
  53829. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  53830. }
  53831. else if (this.poleTargetMesh) {
  53832. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  53833. }
  53834. var bonePos = BoneIKController._tmpVecs[0];
  53835. var zaxis = BoneIKController._tmpVecs[1];
  53836. var xaxis = BoneIKController._tmpVecs[2];
  53837. var yaxis = BoneIKController._tmpVecs[3];
  53838. var upAxis = BoneIKController._tmpVecs[4];
  53839. var _tmpQuat = BoneIKController._tmpQuat;
  53840. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  53841. poleTarget.subtractToRef(bonePos, upAxis);
  53842. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  53843. upAxis.y = 1;
  53844. }
  53845. else {
  53846. upAxis.normalize();
  53847. }
  53848. target.subtractToRef(bonePos, yaxis);
  53849. yaxis.normalize();
  53850. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  53851. zaxis.normalize();
  53852. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  53853. xaxis.normalize();
  53854. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  53855. var a = this._bone1Length;
  53856. var b = this._bone2Length;
  53857. var c = BABYLON.Vector3.Distance(bonePos, target);
  53858. if (this._maxReach > 0) {
  53859. c = Math.min(this._maxReach, c);
  53860. }
  53861. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  53862. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  53863. if (acosa > 1) {
  53864. acosa = 1;
  53865. }
  53866. if (acosb > 1) {
  53867. acosb = 1;
  53868. }
  53869. if (acosa < -1) {
  53870. acosa = -1;
  53871. }
  53872. if (acosb < -1) {
  53873. acosb = -1;
  53874. }
  53875. var angA = Math.acos(acosa);
  53876. var angB = Math.acos(acosb);
  53877. var angC = -angA - angB;
  53878. if (this._rightHandedSystem) {
  53879. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  53880. mat2.multiplyToRef(mat1, mat1);
  53881. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  53882. mat2.multiplyToRef(mat1, mat1);
  53883. }
  53884. else {
  53885. var _tmpVec = BoneIKController._tmpVecs[5];
  53886. _tmpVec.copyFrom(this._bendAxis);
  53887. _tmpVec.x *= -1;
  53888. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  53889. mat2.multiplyToRef(mat1, mat1);
  53890. }
  53891. if (this.poleAngle) {
  53892. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  53893. mat1.multiplyToRef(mat2, mat1);
  53894. }
  53895. if (this.slerpAmount < 1) {
  53896. if (!this._slerping) {
  53897. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  53898. }
  53899. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  53900. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  53901. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  53902. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  53903. this._slerping = true;
  53904. }
  53905. else {
  53906. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  53907. this._bone1Mat.copyFrom(mat1);
  53908. this._slerping = false;
  53909. }
  53910. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  53911. this._bone2Ang = angC;
  53912. };
  53913. return BoneIKController;
  53914. }());
  53915. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  53916. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  53917. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  53918. BABYLON.BoneIKController = BoneIKController;
  53919. })(BABYLON || (BABYLON = {}));
  53920. //# sourceMappingURL=babylon.boneIKController.js.map
  53921. var BABYLON;
  53922. (function (BABYLON) {
  53923. var BoneLookController = (function () {
  53924. /**
  53925. * Create a BoneLookController
  53926. * @param mesh the mesh that the bone belongs to
  53927. * @param bone the bone that will be looking to the target
  53928. * @param target the target Vector3 to look at
  53929. * @param settings optional settings:
  53930. * - maxYaw: the maximum angle the bone will yaw to
  53931. * - minYaw: the minimum angle the bone will yaw to
  53932. * - maxPitch: the maximum angle the bone will pitch to
  53933. * - minPitch: the minimum angle the bone will yaw to
  53934. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  53935. * - upAxis: the up axis of the coordinate system
  53936. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  53937. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  53938. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  53939. * - adjustYaw: used to make an adjustment to the yaw of the bone
  53940. * - adjustPitch: used to make an adjustment to the pitch of the bone
  53941. * - adjustRoll: used to make an adjustment to the roll of the bone
  53942. **/
  53943. function BoneLookController(mesh, bone, target, options) {
  53944. /**
  53945. * The up axis of the coordinate system that is used when the bone is rotated.
  53946. */
  53947. this.upAxis = BABYLON.Vector3.Up();
  53948. /**
  53949. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  53950. */
  53951. this.upAxisSpace = BABYLON.Space.LOCAL;
  53952. /**
  53953. * Used to make an adjustment to the yaw of the bone.
  53954. */
  53955. this.adjustYaw = 0;
  53956. /**
  53957. * Used to make an adjustment to the pitch of the bone.
  53958. */
  53959. this.adjustPitch = 0;
  53960. /**
  53961. * Used to make an adjustment to the roll of the bone.
  53962. */
  53963. this.adjustRoll = 0;
  53964. /**
  53965. * 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).
  53966. */
  53967. this.slerpAmount = 1;
  53968. this._boneQuat = BABYLON.Quaternion.Identity();
  53969. this._slerping = false;
  53970. this._firstFrameSkipped = false;
  53971. this._fowardAxis = BABYLON.Vector3.Forward();
  53972. this.mesh = mesh;
  53973. this.bone = bone;
  53974. this.target = target;
  53975. if (options) {
  53976. if (options.adjustYaw) {
  53977. this.adjustYaw = options.adjustYaw;
  53978. }
  53979. if (options.adjustPitch) {
  53980. this.adjustPitch = options.adjustPitch;
  53981. }
  53982. if (options.adjustRoll) {
  53983. this.adjustRoll = options.adjustRoll;
  53984. }
  53985. if (options.maxYaw != null) {
  53986. this.maxYaw = options.maxYaw;
  53987. }
  53988. else {
  53989. this.maxYaw = Math.PI;
  53990. }
  53991. if (options.minYaw != null) {
  53992. this.minYaw = options.minYaw;
  53993. }
  53994. else {
  53995. this.minYaw = -Math.PI;
  53996. }
  53997. if (options.maxPitch != null) {
  53998. this.maxPitch = options.maxPitch;
  53999. }
  54000. else {
  54001. this.maxPitch = Math.PI;
  54002. }
  54003. if (options.minPitch != null) {
  54004. this.minPitch = options.minPitch;
  54005. }
  54006. else {
  54007. this.minPitch = -Math.PI;
  54008. }
  54009. if (options.slerpAmount != null) {
  54010. this.slerpAmount = options.slerpAmount;
  54011. }
  54012. if (options.upAxis != null) {
  54013. this.upAxis = options.upAxis;
  54014. }
  54015. if (options.upAxisSpace != null) {
  54016. this.upAxisSpace = options.upAxisSpace;
  54017. }
  54018. if (options.yawAxis != null || options.pitchAxis != null) {
  54019. var newYawAxis = BABYLON.Axis.Y;
  54020. var newPitchAxis = BABYLON.Axis.X;
  54021. if (options.yawAxis != null) {
  54022. newYawAxis = options.yawAxis.clone();
  54023. newYawAxis.normalize();
  54024. }
  54025. if (options.pitchAxis != null) {
  54026. newPitchAxis = options.pitchAxis.clone();
  54027. newPitchAxis.normalize();
  54028. }
  54029. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  54030. this._transformYawPitch = BABYLON.Matrix.Identity();
  54031. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  54032. this._transformYawPitchInv = this._transformYawPitch.clone();
  54033. this._transformYawPitch.invert();
  54034. }
  54035. }
  54036. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  54037. this.upAxisSpace = BABYLON.Space.LOCAL;
  54038. }
  54039. }
  54040. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  54041. /**
  54042. * Get/set the minimum yaw angle that the bone can look to.
  54043. */
  54044. get: function () {
  54045. return this._minYaw;
  54046. },
  54047. set: function (value) {
  54048. this._minYaw = value;
  54049. this._minYawSin = Math.sin(value);
  54050. this._minYawCos = Math.cos(value);
  54051. if (this._maxYaw != null) {
  54052. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  54053. this._yawRange = this._maxYaw - this._minYaw;
  54054. }
  54055. },
  54056. enumerable: true,
  54057. configurable: true
  54058. });
  54059. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  54060. /**
  54061. * Get/set the maximum yaw angle that the bone can look to.
  54062. */
  54063. get: function () {
  54064. return this._maxYaw;
  54065. },
  54066. set: function (value) {
  54067. this._maxYaw = value;
  54068. this._maxYawSin = Math.sin(value);
  54069. this._maxYawCos = Math.cos(value);
  54070. if (this._minYaw != null) {
  54071. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  54072. this._yawRange = this._maxYaw - this._minYaw;
  54073. }
  54074. },
  54075. enumerable: true,
  54076. configurable: true
  54077. });
  54078. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  54079. /**
  54080. * Get/set the minimum pitch angle that the bone can look to.
  54081. */
  54082. get: function () {
  54083. return this._minPitch;
  54084. },
  54085. set: function (value) {
  54086. this._minPitch = value;
  54087. this._minPitchTan = Math.tan(value);
  54088. },
  54089. enumerable: true,
  54090. configurable: true
  54091. });
  54092. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  54093. /**
  54094. * Get/set the maximum pitch angle that the bone can look to.
  54095. */
  54096. get: function () {
  54097. return this._maxPitch;
  54098. },
  54099. set: function (value) {
  54100. this._maxPitch = value;
  54101. this._maxPitchTan = Math.tan(value);
  54102. },
  54103. enumerable: true,
  54104. configurable: true
  54105. });
  54106. /**
  54107. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  54108. */
  54109. BoneLookController.prototype.update = function () {
  54110. //skip the first frame when slerping so that the mesh rotation is correct
  54111. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  54112. this._firstFrameSkipped = true;
  54113. return;
  54114. }
  54115. var bone = this.bone;
  54116. var bonePos = BoneLookController._tmpVecs[0];
  54117. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  54118. var target = this.target;
  54119. var _tmpMat1 = BoneLookController._tmpMats[0];
  54120. var _tmpMat2 = BoneLookController._tmpMats[1];
  54121. var mesh = this.mesh;
  54122. var parentBone = bone.getParent();
  54123. var upAxis = BoneLookController._tmpVecs[1];
  54124. upAxis.copyFrom(this.upAxis);
  54125. if (this.upAxisSpace == BABYLON.Space.BONE) {
  54126. if (this._transformYawPitch) {
  54127. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  54128. }
  54129. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  54130. }
  54131. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  54132. mesh.getDirectionToRef(upAxis, upAxis);
  54133. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  54134. upAxis.normalize();
  54135. }
  54136. }
  54137. var checkYaw = false;
  54138. var checkPitch = false;
  54139. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  54140. checkYaw = true;
  54141. }
  54142. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  54143. checkPitch = true;
  54144. }
  54145. if (checkYaw || checkPitch) {
  54146. var spaceMat = BoneLookController._tmpMats[2];
  54147. var spaceMatInv = BoneLookController._tmpMats[3];
  54148. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  54149. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  54150. }
  54151. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  54152. spaceMat.copyFrom(mesh.getWorldMatrix());
  54153. }
  54154. else {
  54155. var forwardAxis = BoneLookController._tmpVecs[2];
  54156. forwardAxis.copyFrom(this._fowardAxis);
  54157. if (this._transformYawPitch) {
  54158. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  54159. }
  54160. if (parentBone) {
  54161. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  54162. }
  54163. else {
  54164. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  54165. }
  54166. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  54167. rightAxis.normalize();
  54168. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  54169. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  54170. }
  54171. spaceMat.invertToRef(spaceMatInv);
  54172. var xzlen;
  54173. if (checkPitch) {
  54174. var localTarget = BoneLookController._tmpVecs[3];
  54175. target.subtractToRef(bonePos, localTarget);
  54176. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  54177. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  54178. var pitch = Math.atan2(localTarget.y, xzlen);
  54179. var newPitch = pitch;
  54180. if (pitch > this._maxPitch) {
  54181. localTarget.y = this._maxPitchTan * xzlen;
  54182. newPitch = this._maxPitch;
  54183. }
  54184. else if (pitch < this._minPitch) {
  54185. localTarget.y = this._minPitchTan * xzlen;
  54186. newPitch = this._minPitch;
  54187. }
  54188. if (pitch != newPitch) {
  54189. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  54190. localTarget.addInPlace(bonePos);
  54191. target = localTarget;
  54192. }
  54193. }
  54194. if (checkYaw) {
  54195. var localTarget = BoneLookController._tmpVecs[4];
  54196. target.subtractToRef(bonePos, localTarget);
  54197. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  54198. var yaw = Math.atan2(localTarget.x, localTarget.z);
  54199. var newYaw = yaw;
  54200. if (yaw > this._maxYaw || yaw < this._minYaw) {
  54201. if (xzlen == null) {
  54202. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  54203. }
  54204. if (this._yawRange > Math.PI) {
  54205. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  54206. localTarget.z = this._maxYawCos * xzlen;
  54207. localTarget.x = this._maxYawSin * xzlen;
  54208. newYaw = this._maxYaw;
  54209. }
  54210. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  54211. localTarget.z = this._minYawCos * xzlen;
  54212. localTarget.x = this._minYawSin * xzlen;
  54213. newYaw = this._minYaw;
  54214. }
  54215. }
  54216. else {
  54217. if (yaw > this._maxYaw) {
  54218. localTarget.z = this._maxYawCos * xzlen;
  54219. localTarget.x = this._maxYawSin * xzlen;
  54220. newYaw = this._maxYaw;
  54221. }
  54222. else if (yaw < this._minYaw) {
  54223. localTarget.z = this._minYawCos * xzlen;
  54224. localTarget.x = this._minYawSin * xzlen;
  54225. newYaw = this._minYaw;
  54226. }
  54227. }
  54228. }
  54229. if (this._slerping && this._yawRange > Math.PI) {
  54230. //are we going to be crossing into the min/max region?
  54231. var boneFwd = BoneLookController._tmpVecs[8];
  54232. boneFwd.copyFrom(BABYLON.Axis.Z);
  54233. if (this._transformYawPitch) {
  54234. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  54235. }
  54236. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  54237. this._boneQuat.toRotationMatrix(boneRotMat);
  54238. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  54239. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  54240. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  54241. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  54242. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  54243. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  54244. if (angBtwTar > angBtwMidYaw) {
  54245. if (xzlen == null) {
  54246. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  54247. }
  54248. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  54249. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  54250. if (angBtwMin < angBtwMax) {
  54251. newYaw = boneYaw + Math.PI * .75;
  54252. localTarget.z = Math.cos(newYaw) * xzlen;
  54253. localTarget.x = Math.sin(newYaw) * xzlen;
  54254. }
  54255. else {
  54256. newYaw = boneYaw - Math.PI * .75;
  54257. localTarget.z = Math.cos(newYaw) * xzlen;
  54258. localTarget.x = Math.sin(newYaw) * xzlen;
  54259. }
  54260. }
  54261. }
  54262. if (yaw != newYaw) {
  54263. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  54264. localTarget.addInPlace(bonePos);
  54265. target = localTarget;
  54266. }
  54267. }
  54268. }
  54269. var zaxis = BoneLookController._tmpVecs[5];
  54270. var xaxis = BoneLookController._tmpVecs[6];
  54271. var yaxis = BoneLookController._tmpVecs[7];
  54272. var _tmpQuat = BoneLookController._tmpQuat;
  54273. target.subtractToRef(bonePos, zaxis);
  54274. zaxis.normalize();
  54275. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  54276. xaxis.normalize();
  54277. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  54278. yaxis.normalize();
  54279. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  54280. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  54281. return;
  54282. }
  54283. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  54284. return;
  54285. }
  54286. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  54287. return;
  54288. }
  54289. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  54290. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  54291. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  54292. }
  54293. if (this.slerpAmount < 1) {
  54294. if (!this._slerping) {
  54295. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  54296. }
  54297. if (this._transformYawPitch) {
  54298. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  54299. }
  54300. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  54301. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  54302. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  54303. this._slerping = true;
  54304. }
  54305. else {
  54306. if (this._transformYawPitch) {
  54307. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  54308. }
  54309. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  54310. this._slerping = false;
  54311. }
  54312. };
  54313. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  54314. var angDiff = ang2 - ang1;
  54315. angDiff %= Math.PI * 2;
  54316. if (angDiff > Math.PI) {
  54317. angDiff -= Math.PI * 2;
  54318. }
  54319. else if (angDiff < -Math.PI) {
  54320. angDiff += Math.PI * 2;
  54321. }
  54322. return angDiff;
  54323. };
  54324. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  54325. ang1 %= (2 * Math.PI);
  54326. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  54327. ang2 %= (2 * Math.PI);
  54328. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  54329. var ab = 0;
  54330. if (ang1 < ang2) {
  54331. ab = ang2 - ang1;
  54332. }
  54333. else {
  54334. ab = ang1 - ang2;
  54335. }
  54336. if (ab > Math.PI) {
  54337. ab = Math.PI * 2 - ab;
  54338. }
  54339. return ab;
  54340. };
  54341. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  54342. ang %= (2 * Math.PI);
  54343. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  54344. ang1 %= (2 * Math.PI);
  54345. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  54346. ang2 %= (2 * Math.PI);
  54347. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  54348. if (ang1 < ang2) {
  54349. if (ang > ang1 && ang < ang2) {
  54350. return true;
  54351. }
  54352. }
  54353. else {
  54354. if (ang > ang2 && ang < ang1) {
  54355. return true;
  54356. }
  54357. }
  54358. return false;
  54359. };
  54360. return BoneLookController;
  54361. }());
  54362. 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()];
  54363. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  54364. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  54365. BABYLON.BoneLookController = BoneLookController;
  54366. })(BABYLON || (BABYLON = {}));
  54367. //# sourceMappingURL=babylon.boneLookController.js.map
  54368. var BABYLON;
  54369. (function (BABYLON) {
  54370. var Skeleton = (function () {
  54371. function Skeleton(name, id, scene) {
  54372. this.name = name;
  54373. this.id = id;
  54374. this.bones = new Array();
  54375. this.needInitialSkinMatrix = false;
  54376. this._isDirty = true;
  54377. this._meshesWithPoseMatrix = new Array();
  54378. this._identity = BABYLON.Matrix.Identity();
  54379. this._ranges = {};
  54380. this._lastAbsoluteTransformsUpdateId = -1;
  54381. // Events
  54382. /**
  54383. * An event triggered before computing the skeleton's matrices
  54384. * @type {BABYLON.Observable}
  54385. */
  54386. this.onBeforeComputeObservable = new BABYLON.Observable();
  54387. this.bones = [];
  54388. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54389. scene.skeletons.push(this);
  54390. //make sure it will recalculate the matrix next time prepare is called.
  54391. this._isDirty = true;
  54392. }
  54393. // Members
  54394. Skeleton.prototype.getTransformMatrices = function (mesh) {
  54395. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  54396. return mesh._bonesTransformMatrices;
  54397. }
  54398. if (!this._transformMatrices) {
  54399. this.prepare();
  54400. }
  54401. return this._transformMatrices;
  54402. };
  54403. Skeleton.prototype.getScene = function () {
  54404. return this._scene;
  54405. };
  54406. // Methods
  54407. /**
  54408. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  54409. */
  54410. Skeleton.prototype.toString = function (fullDetails) {
  54411. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  54412. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  54413. if (fullDetails) {
  54414. ret += ", Ranges: {";
  54415. var first = true;
  54416. for (var name_1 in this._ranges) {
  54417. if (first) {
  54418. ret += ", ";
  54419. first = false;
  54420. }
  54421. ret += name_1;
  54422. }
  54423. ret += "}";
  54424. }
  54425. return ret;
  54426. };
  54427. /**
  54428. * Get bone's index searching by name
  54429. * @param {string} name is bone's name to search for
  54430. * @return {number} Indice of the bone. Returns -1 if not found
  54431. */
  54432. Skeleton.prototype.getBoneIndexByName = function (name) {
  54433. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  54434. if (this.bones[boneIndex].name === name) {
  54435. return boneIndex;
  54436. }
  54437. }
  54438. return -1;
  54439. };
  54440. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  54441. // check name not already in use
  54442. if (!this._ranges[name]) {
  54443. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  54444. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  54445. if (this.bones[i].animations[0]) {
  54446. this.bones[i].animations[0].createRange(name, from, to);
  54447. }
  54448. }
  54449. }
  54450. };
  54451. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  54452. if (deleteFrames === void 0) { deleteFrames = true; }
  54453. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  54454. if (this.bones[i].animations[0]) {
  54455. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  54456. }
  54457. }
  54458. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  54459. };
  54460. Skeleton.prototype.getAnimationRange = function (name) {
  54461. return this._ranges[name];
  54462. };
  54463. /**
  54464. * Returns as an Array, all AnimationRanges defined on this skeleton
  54465. */
  54466. Skeleton.prototype.getAnimationRanges = function () {
  54467. var animationRanges = [];
  54468. var name;
  54469. var i = 0;
  54470. for (name in this._ranges) {
  54471. animationRanges[i] = this._ranges[name];
  54472. i++;
  54473. }
  54474. return animationRanges;
  54475. };
  54476. /**
  54477. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  54478. */
  54479. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  54480. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  54481. if (this._ranges[name] || !source.getAnimationRange(name)) {
  54482. return false;
  54483. }
  54484. var ret = true;
  54485. var frameOffset = this._getHighestAnimationFrame() + 1;
  54486. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  54487. var boneDict = {};
  54488. var sourceBones = source.bones;
  54489. var nBones;
  54490. var i;
  54491. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  54492. boneDict[sourceBones[i].name] = sourceBones[i];
  54493. }
  54494. if (this.bones.length !== sourceBones.length) {
  54495. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  54496. ret = false;
  54497. }
  54498. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  54499. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  54500. var boneName = this.bones[i].name;
  54501. var sourceBone = boneDict[boneName];
  54502. if (sourceBone) {
  54503. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  54504. }
  54505. else {
  54506. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  54507. ret = false;
  54508. }
  54509. }
  54510. // do not call createAnimationRange(), since it also is done to bones, which was already done
  54511. var range = source.getAnimationRange(name);
  54512. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  54513. return ret;
  54514. };
  54515. Skeleton.prototype.returnToRest = function () {
  54516. for (var index = 0; index < this.bones.length; index++) {
  54517. this.bones[index].returnToRest();
  54518. }
  54519. };
  54520. Skeleton.prototype._getHighestAnimationFrame = function () {
  54521. var ret = 0;
  54522. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  54523. if (this.bones[i].animations[0]) {
  54524. var highest = this.bones[i].animations[0].getHighestFrame();
  54525. if (ret < highest) {
  54526. ret = highest;
  54527. }
  54528. }
  54529. }
  54530. return ret;
  54531. };
  54532. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  54533. var range = this.getAnimationRange(name);
  54534. if (!range) {
  54535. return null;
  54536. }
  54537. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  54538. };
  54539. Skeleton.prototype._markAsDirty = function () {
  54540. this._isDirty = true;
  54541. };
  54542. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  54543. this._meshesWithPoseMatrix.push(mesh);
  54544. };
  54545. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  54546. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  54547. if (index > -1) {
  54548. this._meshesWithPoseMatrix.splice(index, 1);
  54549. }
  54550. };
  54551. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  54552. this.onBeforeComputeObservable.notifyObservers(this);
  54553. for (var index = 0; index < this.bones.length; index++) {
  54554. var bone = this.bones[index];
  54555. var parentBone = bone.getParent();
  54556. if (parentBone) {
  54557. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  54558. }
  54559. else {
  54560. if (initialSkinMatrix) {
  54561. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  54562. }
  54563. else {
  54564. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  54565. }
  54566. }
  54567. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  54568. }
  54569. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  54570. };
  54571. Skeleton.prototype.prepare = function () {
  54572. if (!this._isDirty) {
  54573. return;
  54574. }
  54575. if (this.needInitialSkinMatrix) {
  54576. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  54577. var mesh = this._meshesWithPoseMatrix[index];
  54578. var poseMatrix = mesh.getPoseMatrix();
  54579. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  54580. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  54581. }
  54582. if (this._synchronizedWithMesh !== mesh) {
  54583. this._synchronizedWithMesh = mesh;
  54584. // Prepare bones
  54585. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  54586. var bone = this.bones[boneIndex];
  54587. if (!bone.getParent()) {
  54588. var matrix = bone.getBaseMatrix();
  54589. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  54590. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  54591. }
  54592. }
  54593. }
  54594. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  54595. }
  54596. }
  54597. else {
  54598. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  54599. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  54600. }
  54601. this._computeTransformMatrices(this._transformMatrices, null);
  54602. }
  54603. this._isDirty = false;
  54604. this._scene._activeBones.addCount(this.bones.length, false);
  54605. };
  54606. Skeleton.prototype.getAnimatables = function () {
  54607. if (!this._animatables || this._animatables.length !== this.bones.length) {
  54608. this._animatables = [];
  54609. for (var index = 0; index < this.bones.length; index++) {
  54610. this._animatables.push(this.bones[index]);
  54611. }
  54612. }
  54613. return this._animatables;
  54614. };
  54615. Skeleton.prototype.clone = function (name, id) {
  54616. var result = new Skeleton(name, id || name, this._scene);
  54617. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  54618. for (var index = 0; index < this.bones.length; index++) {
  54619. var source = this.bones[index];
  54620. var parentBone = null;
  54621. if (source.getParent()) {
  54622. var parentIndex = this.bones.indexOf(source.getParent());
  54623. parentBone = result.bones[parentIndex];
  54624. }
  54625. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  54626. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  54627. }
  54628. if (this._ranges) {
  54629. result._ranges = {};
  54630. for (var rangeName in this._ranges) {
  54631. result._ranges[rangeName] = this._ranges[rangeName].clone();
  54632. }
  54633. }
  54634. this._isDirty = true;
  54635. return result;
  54636. };
  54637. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  54638. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  54639. this.bones.forEach(function (bone) {
  54640. bone.animations.forEach(function (animation) {
  54641. animation.enableBlending = true;
  54642. animation.blendingSpeed = blendingSpeed;
  54643. });
  54644. });
  54645. };
  54646. Skeleton.prototype.dispose = function () {
  54647. this._meshesWithPoseMatrix = [];
  54648. // Animations
  54649. this.getScene().stopAnimation(this);
  54650. // Remove from scene
  54651. this.getScene().removeSkeleton(this);
  54652. };
  54653. Skeleton.prototype.serialize = function () {
  54654. var serializationObject = {};
  54655. serializationObject.name = this.name;
  54656. serializationObject.id = this.id;
  54657. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  54658. serializationObject.bones = [];
  54659. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  54660. for (var index = 0; index < this.bones.length; index++) {
  54661. var bone = this.bones[index];
  54662. var serializedBone = {
  54663. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  54664. name: bone.name,
  54665. matrix: bone.getBaseMatrix().toArray(),
  54666. rest: bone.getRestPose().toArray()
  54667. };
  54668. serializationObject.bones.push(serializedBone);
  54669. if (bone.length) {
  54670. serializedBone.length = bone.length;
  54671. }
  54672. if (bone.animations && bone.animations.length > 0) {
  54673. serializedBone.animation = bone.animations[0].serialize();
  54674. }
  54675. serializationObject.ranges = [];
  54676. for (var name in this._ranges) {
  54677. var range = {};
  54678. range.name = name;
  54679. range.from = this._ranges[name].from;
  54680. range.to = this._ranges[name].to;
  54681. serializationObject.ranges.push(range);
  54682. }
  54683. }
  54684. return serializationObject;
  54685. };
  54686. Skeleton.Parse = function (parsedSkeleton, scene) {
  54687. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  54688. if (parsedSkeleton.dimensionsAtRest) {
  54689. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  54690. }
  54691. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  54692. var index;
  54693. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  54694. var parsedBone = parsedSkeleton.bones[index];
  54695. var parentBone = null;
  54696. if (parsedBone.parentBoneIndex > -1) {
  54697. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  54698. }
  54699. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  54700. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  54701. if (parsedBone.length) {
  54702. bone.length = parsedBone.length;
  54703. }
  54704. if (parsedBone.animation) {
  54705. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  54706. }
  54707. }
  54708. // placed after bones, so createAnimationRange can cascade down
  54709. if (parsedSkeleton.ranges) {
  54710. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  54711. var data = parsedSkeleton.ranges[index];
  54712. skeleton.createAnimationRange(data.name, data.from, data.to);
  54713. }
  54714. }
  54715. return skeleton;
  54716. };
  54717. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  54718. if (forceUpdate === void 0) { forceUpdate = false; }
  54719. var renderId = this._scene.getRenderId();
  54720. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  54721. this.bones[0].computeAbsoluteTransforms();
  54722. this._lastAbsoluteTransformsUpdateId = renderId;
  54723. }
  54724. };
  54725. Skeleton.prototype.getPoseMatrix = function () {
  54726. var poseMatrix;
  54727. if (this._meshesWithPoseMatrix.length > 0) {
  54728. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  54729. }
  54730. return poseMatrix;
  54731. };
  54732. return Skeleton;
  54733. }());
  54734. BABYLON.Skeleton = Skeleton;
  54735. })(BABYLON || (BABYLON = {}));
  54736. //# sourceMappingURL=babylon.skeleton.js.map
  54737. var BABYLON;
  54738. (function (BABYLON) {
  54739. var Internals;
  54740. (function (Internals) {
  54741. var FileFaceOrientation = (function () {
  54742. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  54743. this.name = name;
  54744. this.worldAxisForNormal = worldAxisForNormal;
  54745. this.worldAxisForFileX = worldAxisForFileX;
  54746. this.worldAxisForFileY = worldAxisForFileY;
  54747. }
  54748. return FileFaceOrientation;
  54749. }());
  54750. ;
  54751. /**
  54752. * Helper class dealing with the extraction of spherical polynomial dataArray
  54753. * from a cube map.
  54754. */
  54755. var CubeMapToSphericalPolynomialTools = (function () {
  54756. function CubeMapToSphericalPolynomialTools() {
  54757. }
  54758. /**
  54759. * Converts a cubemap to the according Spherical Polynomial data.
  54760. * This extracts the first 3 orders only as they are the only one used in the lighting.
  54761. *
  54762. * @param cubeInfo The Cube map to extract the information from.
  54763. * @return The Spherical Polynomial data.
  54764. */
  54765. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  54766. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  54767. var totalSolidAngle = 0.0;
  54768. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  54769. var du = 2.0 / cubeInfo.size;
  54770. var dv = du;
  54771. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  54772. var minUV = du * 0.5 - 1.0;
  54773. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54774. var fileFace = this.FileFaces[faceIndex];
  54775. var dataArray = cubeInfo[fileFace.name];
  54776. var v = minUV;
  54777. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  54778. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  54779. // Because SP is still linear, so summation is fine in that basis.
  54780. for (var y = 0; y < cubeInfo.size; y++) {
  54781. var u = minUV;
  54782. for (var x = 0; x < cubeInfo.size; x++) {
  54783. // World direction (not normalised)
  54784. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  54785. worldDirection.normalize();
  54786. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  54787. if (1) {
  54788. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  54789. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  54790. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  54791. var color = new BABYLON.Color3(r, g, b);
  54792. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  54793. }
  54794. else {
  54795. if (faceIndex == 0) {
  54796. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54797. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54798. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54799. }
  54800. else if (faceIndex == 1) {
  54801. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54802. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54803. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54804. }
  54805. else if (faceIndex == 2) {
  54806. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54807. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54808. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54809. }
  54810. else if (faceIndex == 3) {
  54811. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54812. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54813. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54814. }
  54815. else if (faceIndex == 4) {
  54816. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54817. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54818. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54819. }
  54820. else if (faceIndex == 5) {
  54821. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54822. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54823. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54824. }
  54825. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  54826. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  54827. }
  54828. totalSolidAngle += deltaSolidAngle;
  54829. u += du;
  54830. }
  54831. v += dv;
  54832. }
  54833. }
  54834. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  54835. var correction = correctSolidAngle / totalSolidAngle;
  54836. sphericalHarmonics.scale(correction);
  54837. // Additionally scale by pi -- audit needed
  54838. sphericalHarmonics.scale(1.0 / Math.PI);
  54839. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  54840. };
  54841. return CubeMapToSphericalPolynomialTools;
  54842. }());
  54843. CubeMapToSphericalPolynomialTools.FileFaces = [
  54844. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  54845. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  54846. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  54847. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  54848. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  54849. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  54850. ];
  54851. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  54852. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54853. })(BABYLON || (BABYLON = {}));
  54854. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  54855. var BABYLON;
  54856. (function (BABYLON) {
  54857. var Internals;
  54858. (function (Internals) {
  54859. /**
  54860. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  54861. */
  54862. var PanoramaToCubeMapTools = (function () {
  54863. function PanoramaToCubeMapTools() {
  54864. }
  54865. /**
  54866. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  54867. *
  54868. * @param float32Array The source data.
  54869. * @param inputWidth The width of the input panorama.
  54870. * @param inputhHeight The height of the input panorama.
  54871. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  54872. * @return The cubemap data
  54873. */
  54874. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  54875. if (!float32Array) {
  54876. throw "ConvertPanoramaToCubemap: input cannot be null";
  54877. }
  54878. if (float32Array.length != inputWidth * inputHeight * 3) {
  54879. throw "ConvertPanoramaToCubemap: input size is wrong";
  54880. }
  54881. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  54882. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  54883. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  54884. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  54885. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  54886. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  54887. return {
  54888. front: textureFront,
  54889. back: textureBack,
  54890. left: textureLeft,
  54891. right: textureRight,
  54892. up: textureUp,
  54893. down: textureDown,
  54894. size: size
  54895. };
  54896. };
  54897. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  54898. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  54899. var textureArray = new Float32Array(buffer);
  54900. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  54901. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  54902. var dy = 1 / texSize;
  54903. var fy = 0;
  54904. for (var y = 0; y < texSize; y++) {
  54905. var xv1 = faceData[0];
  54906. var xv2 = faceData[2];
  54907. for (var x = 0; x < texSize; x++) {
  54908. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  54909. v.normalize();
  54910. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  54911. // 3 channels per pixels
  54912. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  54913. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  54914. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  54915. xv1 = xv1.add(rotDX1);
  54916. xv2 = xv2.add(rotDX2);
  54917. }
  54918. fy += dy;
  54919. }
  54920. return textureArray;
  54921. };
  54922. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  54923. var theta = Math.atan2(vDir.z, vDir.x);
  54924. var phi = Math.acos(vDir.y);
  54925. while (theta < -Math.PI)
  54926. theta += 2 * Math.PI;
  54927. while (theta > Math.PI)
  54928. theta -= 2 * Math.PI;
  54929. var dx = theta / Math.PI;
  54930. var dy = phi / Math.PI;
  54931. // recenter.
  54932. dx = dx * 0.5 + 0.5;
  54933. var px = Math.round(dx * inputWidth);
  54934. if (px < 0)
  54935. px = 0;
  54936. else if (px >= inputWidth)
  54937. px = inputWidth - 1;
  54938. var py = Math.round(dy * inputHeight);
  54939. if (py < 0)
  54940. py = 0;
  54941. else if (py >= inputHeight)
  54942. py = inputHeight - 1;
  54943. var inputY = (inputHeight - py - 1);
  54944. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  54945. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  54946. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  54947. return {
  54948. r: r,
  54949. g: g,
  54950. b: b
  54951. };
  54952. };
  54953. return PanoramaToCubeMapTools;
  54954. }());
  54955. PanoramaToCubeMapTools.FACE_FRONT = [
  54956. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  54957. new BABYLON.Vector3(1.0, -1.0, -1.0),
  54958. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  54959. new BABYLON.Vector3(1.0, 1.0, -1.0)
  54960. ];
  54961. PanoramaToCubeMapTools.FACE_BACK = [
  54962. new BABYLON.Vector3(1.0, -1.0, 1.0),
  54963. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  54964. new BABYLON.Vector3(1.0, 1.0, 1.0),
  54965. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  54966. ];
  54967. PanoramaToCubeMapTools.FACE_RIGHT = [
  54968. new BABYLON.Vector3(1.0, -1.0, -1.0),
  54969. new BABYLON.Vector3(1.0, -1.0, 1.0),
  54970. new BABYLON.Vector3(1.0, 1.0, -1.0),
  54971. new BABYLON.Vector3(1.0, 1.0, 1.0)
  54972. ];
  54973. PanoramaToCubeMapTools.FACE_LEFT = [
  54974. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  54975. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  54976. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  54977. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  54978. ];
  54979. PanoramaToCubeMapTools.FACE_DOWN = [
  54980. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  54981. new BABYLON.Vector3(1.0, 1.0, -1.0),
  54982. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  54983. new BABYLON.Vector3(1.0, 1.0, 1.0)
  54984. ];
  54985. PanoramaToCubeMapTools.FACE_UP = [
  54986. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  54987. new BABYLON.Vector3(1.0, -1.0, 1.0),
  54988. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  54989. new BABYLON.Vector3(1.0, -1.0, -1.0)
  54990. ];
  54991. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  54992. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54993. })(BABYLON || (BABYLON = {}));
  54994. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  54995. var BABYLON;
  54996. (function (BABYLON) {
  54997. var Internals;
  54998. (function (Internals) {
  54999. ;
  55000. /**
  55001. * This groups tools to convert HDR texture to native colors array.
  55002. */
  55003. var HDRTools = (function () {
  55004. function HDRTools() {
  55005. }
  55006. HDRTools.Ldexp = function (mantissa, exponent) {
  55007. if (exponent > 1023) {
  55008. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  55009. }
  55010. if (exponent < -1074) {
  55011. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  55012. }
  55013. return mantissa * Math.pow(2, exponent);
  55014. };
  55015. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  55016. if (exponent > 0) {
  55017. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  55018. float32array[index + 0] = red * exponent;
  55019. float32array[index + 1] = green * exponent;
  55020. float32array[index + 2] = blue * exponent;
  55021. }
  55022. else {
  55023. float32array[index + 0] = 0;
  55024. float32array[index + 1] = 0;
  55025. float32array[index + 2] = 0;
  55026. }
  55027. };
  55028. HDRTools.readStringLine = function (uint8array, startIndex) {
  55029. var line = "";
  55030. var character = "";
  55031. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  55032. character = String.fromCharCode(uint8array[i]);
  55033. if (character == "\n") {
  55034. break;
  55035. }
  55036. line += character;
  55037. }
  55038. return line;
  55039. };
  55040. /**
  55041. * Reads header information from an RGBE texture stored in a native array.
  55042. * More information on this format are available here:
  55043. * https://en.wikipedia.org/wiki/RGBE_image_format
  55044. *
  55045. * @param uint8array The binary file stored in native array.
  55046. * @return The header information.
  55047. */
  55048. HDRTools.RGBE_ReadHeader = function (uint8array) {
  55049. var height = 0;
  55050. var width = 0;
  55051. var line = this.readStringLine(uint8array, 0);
  55052. if (line[0] != '#' || line[1] != '?') {
  55053. throw "Bad HDR Format.";
  55054. }
  55055. var endOfHeader = false;
  55056. var findFormat = false;
  55057. var lineIndex = 0;
  55058. do {
  55059. lineIndex += (line.length + 1);
  55060. line = this.readStringLine(uint8array, lineIndex);
  55061. if (line == "FORMAT=32-bit_rle_rgbe") {
  55062. findFormat = true;
  55063. }
  55064. else if (line.length == 0) {
  55065. endOfHeader = true;
  55066. }
  55067. } while (!endOfHeader);
  55068. if (!findFormat) {
  55069. throw "HDR Bad header format, unsupported FORMAT";
  55070. }
  55071. lineIndex += (line.length + 1);
  55072. line = this.readStringLine(uint8array, lineIndex);
  55073. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  55074. var match = sizeRegexp.exec(line);
  55075. // TODO. Support +Y and -X if needed.
  55076. if (match.length < 3) {
  55077. throw "HDR Bad header format, no size";
  55078. }
  55079. width = parseInt(match[2]);
  55080. height = parseInt(match[1]);
  55081. if (width < 8 || width > 0x7fff) {
  55082. throw "HDR Bad header format, unsupported size";
  55083. }
  55084. lineIndex += (line.length + 1);
  55085. return {
  55086. height: height,
  55087. width: width,
  55088. dataPosition: lineIndex
  55089. };
  55090. };
  55091. /**
  55092. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  55093. * This RGBE texture needs to store the information as a panorama.
  55094. *
  55095. * More information on this format are available here:
  55096. * https://en.wikipedia.org/wiki/RGBE_image_format
  55097. *
  55098. * @param buffer The binary file stored in an array buffer.
  55099. * @param size The expected size of the extracted cubemap.
  55100. * @return The Cube Map information.
  55101. */
  55102. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  55103. var uint8array = new Uint8Array(buffer);
  55104. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  55105. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55106. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  55107. return cubeMapData;
  55108. };
  55109. /**
  55110. * Returns the pixels data extracted from an RGBE texture.
  55111. * This pixels will be stored left to right up to down in the R G B order in one array.
  55112. *
  55113. * More information on this format are available here:
  55114. * https://en.wikipedia.org/wiki/RGBE_image_format
  55115. *
  55116. * @param uint8array The binary file stored in an array buffer.
  55117. * @param hdrInfo The header information of the file.
  55118. * @return The pixels data in RGB right to left up to down order.
  55119. */
  55120. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  55121. // Keep for multi format supports.
  55122. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55123. };
  55124. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  55125. var num_scanlines = hdrInfo.height;
  55126. var scanline_width = hdrInfo.width;
  55127. var a, b, c, d, count;
  55128. var dataIndex = hdrInfo.dataPosition;
  55129. var index = 0, endIndex = 0, i = 0;
  55130. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  55131. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  55132. // 3 channels of 4 bytes per pixel in float.
  55133. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  55134. var resultArray = new Float32Array(resultBuffer);
  55135. // read in each successive scanline
  55136. while (num_scanlines > 0) {
  55137. a = uint8array[dataIndex++];
  55138. b = uint8array[dataIndex++];
  55139. c = uint8array[dataIndex++];
  55140. d = uint8array[dataIndex++];
  55141. if (a != 2 || b != 2 || (c & 0x80)) {
  55142. // this file is not run length encoded
  55143. throw "HDR Bad header format, not RLE";
  55144. }
  55145. if (((c << 8) | d) != scanline_width) {
  55146. throw "HDR Bad header format, wrong scan line width";
  55147. }
  55148. index = 0;
  55149. // read each of the four channels for the scanline into the buffer
  55150. for (i = 0; i < 4; i++) {
  55151. endIndex = (i + 1) * scanline_width;
  55152. while (index < endIndex) {
  55153. a = uint8array[dataIndex++];
  55154. b = uint8array[dataIndex++];
  55155. if (a > 128) {
  55156. // a run of the same value
  55157. count = a - 128;
  55158. if ((count == 0) || (count > endIndex - index)) {
  55159. throw "HDR Bad Format, bad scanline data (run)";
  55160. }
  55161. while (count-- > 0) {
  55162. scanLineArray[index++] = b;
  55163. }
  55164. }
  55165. else {
  55166. // a non-run
  55167. count = a;
  55168. if ((count == 0) || (count > endIndex - index)) {
  55169. throw "HDR Bad Format, bad scanline data (non-run)";
  55170. }
  55171. scanLineArray[index++] = b;
  55172. if (--count > 0) {
  55173. for (var j = 0; j < count; j++) {
  55174. scanLineArray[index++] = uint8array[dataIndex++];
  55175. }
  55176. }
  55177. }
  55178. }
  55179. }
  55180. // now convert data from buffer into floats
  55181. for (i = 0; i < scanline_width; i++) {
  55182. a = scanLineArray[i];
  55183. b = scanLineArray[i + scanline_width];
  55184. c = scanLineArray[i + 2 * scanline_width];
  55185. d = scanLineArray[i + 3 * scanline_width];
  55186. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  55187. }
  55188. num_scanlines--;
  55189. }
  55190. return resultArray;
  55191. };
  55192. return HDRTools;
  55193. }());
  55194. Internals.HDRTools = HDRTools;
  55195. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55196. })(BABYLON || (BABYLON = {}));
  55197. //# sourceMappingURL=babylon.hdr.js.map
  55198. //_______________________________________________________________
  55199. // Extracted from CubeMapGen:
  55200. // https://code.google.com/archive/p/cubemapgen/
  55201. //
  55202. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55203. //_______________________________________________________________
  55204. var BABYLON;
  55205. (function (BABYLON) {
  55206. var Internals;
  55207. (function (Internals) {
  55208. /**
  55209. * The bounding box information used during the conversion process.
  55210. */
  55211. var CMGBoundinBox = (function () {
  55212. function CMGBoundinBox() {
  55213. this.min = new BABYLON.Vector3(0, 0, 0);
  55214. this.max = new BABYLON.Vector3(0, 0, 0);
  55215. this.clear();
  55216. }
  55217. CMGBoundinBox.prototype.clear = function () {
  55218. this.min.x = CMGBoundinBox.MAX;
  55219. this.min.y = CMGBoundinBox.MAX;
  55220. this.min.z = CMGBoundinBox.MAX;
  55221. this.max.x = CMGBoundinBox.MIN;
  55222. this.max.y = CMGBoundinBox.MIN;
  55223. this.max.z = CMGBoundinBox.MIN;
  55224. };
  55225. CMGBoundinBox.prototype.augment = function (x, y, z) {
  55226. this.min.x = Math.min(this.min.x, x);
  55227. this.min.y = Math.min(this.min.y, y);
  55228. this.min.z = Math.min(this.min.z, z);
  55229. this.max.x = Math.max(this.max.x, x);
  55230. this.max.y = Math.max(this.max.y, y);
  55231. this.max.z = Math.max(this.max.z, z);
  55232. };
  55233. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  55234. this.min.x = Math.max(this.min.x, x);
  55235. this.min.y = Math.max(this.min.y, y);
  55236. this.min.z = Math.max(this.min.z, z);
  55237. };
  55238. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  55239. this.max.x = Math.min(this.max.x, x);
  55240. this.max.y = Math.min(this.max.y, y);
  55241. this.max.z = Math.min(this.max.z, z);
  55242. };
  55243. CMGBoundinBox.prototype.empty = function () {
  55244. if ((this.min.x > this.max.y) ||
  55245. (this.min.y > this.max.y) ||
  55246. (this.min.z > this.max.y)) {
  55247. return true;
  55248. }
  55249. else {
  55250. return false;
  55251. }
  55252. };
  55253. return CMGBoundinBox;
  55254. }());
  55255. CMGBoundinBox.MAX = Number.MAX_VALUE;
  55256. CMGBoundinBox.MIN = Number.MIN_VALUE;
  55257. /**
  55258. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  55259. * required by the glossinees of a material.
  55260. *
  55261. * This only supports the cosine drop power as well as Warp fixup generation method.
  55262. *
  55263. * This is using the process from CubeMapGen described here:
  55264. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55265. */
  55266. var PMREMGenerator = (function () {
  55267. /**
  55268. * Constructor of the generator.
  55269. *
  55270. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  55271. * @param inputSize The size of the cubemap faces
  55272. * @param outputSize The size of the output cubemap faces
  55273. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  55274. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  55275. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  55276. * @param specularPower The max specular level of the desired cubemap
  55277. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  55278. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  55279. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  55280. */
  55281. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  55282. this.input = input;
  55283. this.inputSize = inputSize;
  55284. this.outputSize = outputSize;
  55285. this.maxNumMipLevels = maxNumMipLevels;
  55286. this.numChannels = numChannels;
  55287. this.isFloat = isFloat;
  55288. this.specularPower = specularPower;
  55289. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  55290. this.excludeBase = excludeBase;
  55291. this.fixup = fixup;
  55292. this._outputSurface = [];
  55293. this._numMipLevels = 0;
  55294. }
  55295. /**
  55296. * Launches the filter process and return the result.
  55297. *
  55298. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  55299. */
  55300. PMREMGenerator.prototype.filterCubeMap = function () {
  55301. // Init cubemap processor
  55302. this.init();
  55303. // Filters the cubemap
  55304. this.filterCubeMapMipChain();
  55305. // Returns the filtered mips.
  55306. return this._outputSurface;
  55307. };
  55308. PMREMGenerator.prototype.init = function () {
  55309. var i;
  55310. var j;
  55311. var mipLevelSize;
  55312. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  55313. if (this.maxNumMipLevels == 0) {
  55314. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  55315. }
  55316. //first miplevel size
  55317. mipLevelSize = this.outputSize;
  55318. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  55319. for (j = 0; j < this.maxNumMipLevels; j++) {
  55320. this._outputSurface.length++;
  55321. this._outputSurface[j] = [];
  55322. //Iterate over faces for output images
  55323. for (i = 0; i < 6; i++) {
  55324. this._outputSurface[j].length++;
  55325. // Initializes a new array for the output.
  55326. if (this.isFloat) {
  55327. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55328. }
  55329. else {
  55330. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55331. }
  55332. }
  55333. //next mip level is half size
  55334. mipLevelSize >>= 1;
  55335. this._numMipLevels++;
  55336. //terminate if mip chain becomes too small
  55337. if (mipLevelSize == 0) {
  55338. this.maxNumMipLevels = j;
  55339. return;
  55340. }
  55341. }
  55342. };
  55343. //--------------------------------------------------------------------------------------
  55344. //Cube map filtering and mip chain generation.
  55345. // the cube map filtereing is specified using a number of parameters:
  55346. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  55347. // indicates the region of the hemisphere to filter over for each tap.
  55348. //
  55349. // Note that the top mip level is also a filtered version of the original input images
  55350. // as well in order to create mip chains for diffuse environment illumination.
  55351. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  55352. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  55353. //
  55354. // Then the mip angle used to genreate the next level of the mip chain from the first level
  55355. // is a_InitialMipAngle
  55356. //
  55357. // The angle for the subsequent levels of the mip chain are specified by their parents
  55358. // filtering angle and a per-level scale and bias
  55359. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  55360. //
  55361. //--------------------------------------------------------------------------------------
  55362. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  55363. // First, take count of the lighting model to modify SpecularPower
  55364. // var refSpecularPower = (a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN || a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? a_MCO.SpecularPower / GetSpecularPowerFactorToMatchPhong(a_MCO.SpecularPower) : a_MCO.SpecularPower;
  55365. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  55366. //Cone angle start (for generating subsequent mip levels)
  55367. var currentSpecularPower = this.specularPower;
  55368. //Build filter lookup tables based on the source miplevel size
  55369. this.precomputeFilterLookupTables(this.inputSize);
  55370. // Note that we need to filter the first level before generating mipmap
  55371. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  55372. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  55373. // TODO : Write a function to copy and scale the base mipmap in output
  55374. // I am just lazy here and just put a high specular power value, and do some if.
  55375. if (this.excludeBase && (levelIndex == 0)) {
  55376. // If we don't want to process the base mipmap, just put a very high specular power (this allow to handle scale of the texture).
  55377. currentSpecularPower = 100000.0;
  55378. }
  55379. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  55380. var srcCubeImage = this.input;
  55381. var dstCubeImage = this._outputSurface[levelIndex];
  55382. var dstSize = this.outputSize >> levelIndex;
  55383. // Compute required angle.
  55384. var angle = this.getBaseFilterAngle(currentSpecularPower);
  55385. // filter cube surfaces
  55386. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  55387. // fix seams
  55388. if (this.fixup) {
  55389. this.fixupCubeEdges(dstCubeImage, dstSize);
  55390. }
  55391. // Decrease the specular power to generate the mipmap chain
  55392. // TODO : Use another method for Exclude (see first comment at start of the function
  55393. if (this.excludeBase && (levelIndex == 0)) {
  55394. currentSpecularPower = this.specularPower;
  55395. }
  55396. currentSpecularPower *= this.cosinePowerDropPerMip;
  55397. }
  55398. };
  55399. //--------------------------------------------------------------------------------------
  55400. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  55401. // It allow to optimize the texel to access base on the specular power.
  55402. //--------------------------------------------------------------------------------------
  55403. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  55404. // We want to find the alpha such that:
  55405. // cos(alpha)^cosinePower = epsilon
  55406. // That's: acos(epsilon^(1/cosinePower))
  55407. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  55408. var angle = 180.0;
  55409. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  55410. angle *= 180.0 / Math.PI; // Convert to degree
  55411. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  55412. return angle;
  55413. };
  55414. //--------------------------------------------------------------------------------------
  55415. //Builds the following lookup tables prior to filtering:
  55416. // -normalizer cube map
  55417. // -tap weight lookup table
  55418. //
  55419. //--------------------------------------------------------------------------------------
  55420. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  55421. var srcTexelAngle;
  55422. var iCubeFace;
  55423. //clear pre-existing normalizer cube map
  55424. this._normCubeMap = [];
  55425. //Normalized vectors per cubeface and per-texel solid angle
  55426. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  55427. };
  55428. //--------------------------------------------------------------------------------------
  55429. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  55430. //
  55431. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  55432. //
  55433. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  55434. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  55435. // below
  55436. //--------------------------------------------------------------------------------------
  55437. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  55438. var iCubeFace;
  55439. var u;
  55440. var v;
  55441. //iterate over cube faces
  55442. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55443. //First three channels for norm cube, and last channel for solid angle
  55444. this._normCubeMap.push(new Float32Array(size * size * 4));
  55445. //fast texture walk, build normalizer cube map
  55446. var facesData = this.input[iCubeFace];
  55447. for (v = 0; v < size; v++) {
  55448. for (u = 0; u < size; u++) {
  55449. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  55450. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  55451. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  55452. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  55453. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  55454. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  55455. }
  55456. }
  55457. }
  55458. };
  55459. //--------------------------------------------------------------------------------------
  55460. // Convert cubemap face texel coordinates and face idx to 3D vector
  55461. // note the U and V coords are integer coords and range from 0 to size-1
  55462. // this routine can be used to generate a normalizer cube map
  55463. //--------------------------------------------------------------------------------------
  55464. // SL BEGIN
  55465. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  55466. var nvcU;
  55467. var nvcV;
  55468. var tempVec;
  55469. // Change from original AMD code
  55470. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55471. // + 0.5f is for texel center addressing
  55472. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  55473. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  55474. // warp fixup
  55475. if (fixup && size > 1) {
  55476. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  55477. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  55478. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  55479. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  55480. }
  55481. // Get current vector
  55482. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  55483. // U contribution
  55484. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55485. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  55486. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  55487. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  55488. // V contribution and Sum
  55489. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55490. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  55491. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  55492. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  55493. //add face axis
  55494. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  55495. PMREMGenerator._vectorTemp.x += faceAxis[0];
  55496. PMREMGenerator._vectorTemp.y += faceAxis[1];
  55497. PMREMGenerator._vectorTemp.z += faceAxis[2];
  55498. //normalize vector
  55499. PMREMGenerator._vectorTemp.normalize();
  55500. return PMREMGenerator._vectorTemp;
  55501. };
  55502. //--------------------------------------------------------------------------------------
  55503. // Convert 3D vector to cubemap face texel coordinates and face idx
  55504. // note the U and V coords are integer coords and range from 0 to size-1
  55505. // this routine can be used to generate a normalizer cube map
  55506. //
  55507. // returns face IDX and texel coords
  55508. //--------------------------------------------------------------------------------------
  55509. // SL BEGIN
  55510. /*
  55511. Mapping Texture Coordinates to Cube Map Faces
  55512. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  55513. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  55514. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  55515. map arrangement in Pixar's RenderMan package.
  55516. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  55517. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  55518. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  55519. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  55520. the major axis direction). The target column in the table below explains how the major axis direction
  55521. maps to the 2D image of a particular cube map target.
  55522. major axis
  55523. direction target sc tc ma
  55524. ---------- --------------------------------- --- --- ---
  55525. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  55526. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  55527. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  55528. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  55529. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  55530. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  55531. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  55532. an updated (s,t) is calculated as follows
  55533. s = ( sc/|ma| + 1 ) / 2
  55534. t = ( tc/|ma| + 1 ) / 2
  55535. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  55536. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  55537. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  55538. */
  55539. // Note this method return U and V in range from 0 to size-1
  55540. // SL END
  55541. // Store the information in vector3 for convenience (faceindex, u, v)
  55542. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  55543. var maxCoord;
  55544. var faceIdx;
  55545. //absolute value 3
  55546. var absX = Math.abs(x);
  55547. var absY = Math.abs(y);
  55548. var absZ = Math.abs(z);
  55549. if (absX >= absY && absX >= absZ) {
  55550. maxCoord = absX;
  55551. if (x >= 0) {
  55552. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  55553. }
  55554. else {
  55555. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55556. }
  55557. }
  55558. else if (absY >= absX && absY >= absZ) {
  55559. maxCoord = absY;
  55560. if (y >= 0) {
  55561. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55562. }
  55563. else {
  55564. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55565. }
  55566. }
  55567. else {
  55568. maxCoord = absZ;
  55569. if (z >= 0) {
  55570. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55571. }
  55572. else {
  55573. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55574. }
  55575. }
  55576. //divide through by max coord so face vector lies on cube face
  55577. var scale = 1 / maxCoord;
  55578. x *= scale;
  55579. y *= scale;
  55580. z *= scale;
  55581. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55582. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  55583. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55584. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  55585. // Modify original AMD code to return value from 0 to Size - 1
  55586. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  55587. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  55588. PMREMGenerator._vectorTemp.x = faceIdx;
  55589. PMREMGenerator._vectorTemp.y = u;
  55590. PMREMGenerator._vectorTemp.z = v;
  55591. return PMREMGenerator._vectorTemp;
  55592. };
  55593. //--------------------------------------------------------------------------------------
  55594. //Original code from Ignacio CastaÒo
  55595. // This formula is from Manne ÷hrstrˆm's thesis.
  55596. // Take two coordiantes in the range [-1, 1] that define a portion of a
  55597. // cube face and return the area of the projection of that portion on the
  55598. // surface of the sphere.
  55599. //--------------------------------------------------------------------------------------
  55600. PMREMGenerator.prototype.areaElement = function (x, y) {
  55601. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  55602. };
  55603. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  55604. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55605. // (+ 0.5f is for texel center addressing)
  55606. u = (2.0 * (u + 0.5) / size) - 1.0;
  55607. v = (2.0 * (v + 0.5) / size) - 1.0;
  55608. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  55609. var invResolution = 1.0 / size;
  55610. // U and V are the -1..1 texture coordinate on the current face.
  55611. // Get projected area for this texel
  55612. var x0 = u - invResolution;
  55613. var y0 = v - invResolution;
  55614. var x1 = u + invResolution;
  55615. var y1 = v + invResolution;
  55616. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  55617. return solidAngle;
  55618. };
  55619. //--------------------------------------------------------------------------------------
  55620. //The key to the speed of these filtering routines is to quickly define a per-face
  55621. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  55622. // Later these pixels are selectively processed based on their dot products to see if
  55623. // they reside within the filtering cone.
  55624. //
  55625. //This is done by computing the smallest per-texel angle to get a conservative estimate
  55626. // of the number of texels needed to be covered in width and height order to filter the
  55627. // region. the bounding box for the center taps face is defined first, and if the
  55628. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  55629. // defined next
  55630. //--------------------------------------------------------------------------------------
  55631. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  55632. // note that pixels within these regions may be rejected
  55633. // based on the anlge
  55634. var iCubeFace;
  55635. var u;
  55636. var v;
  55637. // bounding box per face to specify region to process
  55638. var filterExtents = [];
  55639. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55640. filterExtents.push(new CMGBoundinBox());
  55641. }
  55642. // min angle a src texel can cover (in degrees)
  55643. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  55644. // angle about center tap to define filter cone
  55645. // filter angle is 1/2 the cone angle
  55646. var filterAngle = filterConeAngle / 2.0;
  55647. //ensure filter angle is larger than a texel
  55648. if (filterAngle < srcTexelAngle) {
  55649. filterAngle = srcTexelAngle;
  55650. }
  55651. //ensure filter cone is always smaller than the hemisphere
  55652. if (filterAngle > 90.0) {
  55653. filterAngle = 90.0;
  55654. }
  55655. // the maximum number of texels in 1D the filter cone angle will cover
  55656. // used to determine bounding box size for filter extents
  55657. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  55658. // ensure conservative region always covers at least one texel
  55659. if (filterSize < 1) {
  55660. filterSize = 1;
  55661. }
  55662. // dotProdThresh threshold based on cone angle to determine whether or not taps
  55663. // reside within the cone angle
  55664. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  55665. // process required faces
  55666. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55667. //iterate over dst cube map face texel
  55668. for (v = 0; v < dstSize; v++) {
  55669. for (u = 0; u < dstSize; u++) {
  55670. //get center tap direction
  55671. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  55672. //clear old per-face filter extents
  55673. this.clearFilterExtents(filterExtents);
  55674. //define per-face filter extents
  55675. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  55676. //perform filtering of src faces using filter extents
  55677. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  55678. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  55679. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  55680. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  55681. }
  55682. }
  55683. }
  55684. };
  55685. //--------------------------------------------------------------------------------------
  55686. //Clear filter extents for the 6 cube map faces
  55687. //--------------------------------------------------------------------------------------
  55688. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  55689. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  55690. filterExtents[iCubeFaces].clear();
  55691. }
  55692. };
  55693. //--------------------------------------------------------------------------------------
  55694. //Define per-face bounding box filter extents
  55695. //
  55696. // These define conservative texel regions in each of the faces the filter can possibly
  55697. // process. When the pixels in the regions are actually processed, the dot product
  55698. // between the tap vector and the center tap vector is used to determine the weight of
  55699. // the tap and whether or not the tap is within the cone.
  55700. //
  55701. //--------------------------------------------------------------------------------------
  55702. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  55703. //neighboring face and bleed over amount, and width of BBOX for
  55704. // left, right, top, and bottom edges of this face
  55705. var bleedOverAmount = [0, 0, 0, 0];
  55706. var bleedOverBBoxMin = [0, 0, 0, 0];
  55707. var bleedOverBBoxMax = [0, 0, 0, 0];
  55708. var neighborFace;
  55709. var neighborEdge;
  55710. var oppositeFaceIdx;
  55711. //get face idx, and u, v info from center tap dir
  55712. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  55713. var faceIdx = result.x;
  55714. var u = result.y;
  55715. var v = result.z;
  55716. //define bbox size within face
  55717. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  55718. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  55719. filterExtents[faceIdx].clampMin(0, 0, 0);
  55720. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  55721. //u and v extent in face corresponding to center tap
  55722. var minU = filterExtents[faceIdx].min.x;
  55723. var minV = filterExtents[faceIdx].min.y;
  55724. var maxU = filterExtents[faceIdx].max.x;
  55725. var maxV = filterExtents[faceIdx].max.y;
  55726. //bleed over amounts for face across u=0 edge (left)
  55727. bleedOverAmount[0] = (bboxSize - u);
  55728. bleedOverBBoxMin[0] = minV;
  55729. bleedOverBBoxMax[0] = maxV;
  55730. //bleed over amounts for face across u=1 edge (right)
  55731. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  55732. bleedOverBBoxMin[1] = minV;
  55733. bleedOverBBoxMax[1] = maxV;
  55734. //bleed over to face across v=0 edge (up)
  55735. bleedOverAmount[2] = (bboxSize - v);
  55736. bleedOverBBoxMin[2] = minU;
  55737. bleedOverBBoxMax[2] = maxU;
  55738. //bleed over to face across v=1 edge (down)
  55739. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  55740. bleedOverBBoxMin[3] = minU;
  55741. bleedOverBBoxMax[3] = maxU;
  55742. //compute bleed over regions in neighboring faces
  55743. for (var i = 0; i < 4; i++) {
  55744. if (bleedOverAmount[i] > 0) {
  55745. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  55746. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  55747. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  55748. // be flipped: the cases are
  55749. // if a left edge mates with a left or bottom edge on the neighbor
  55750. // if a top edge mates with a top or right edge on the neighbor
  55751. // if a right edge mates with a right or top edge on the neighbor
  55752. // if a bottom edge mates with a bottom or left edge on the neighbor
  55753. //Seeing as the edges are enumerated as follows
  55754. // left =0
  55755. // right =1
  55756. // top =2
  55757. // bottom =3
  55758. //
  55759. // so if the edge enums are the same, or the sum of the enums == 3,
  55760. // the bbox needs to be flipped
  55761. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  55762. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  55763. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  55764. }
  55765. //The way the bounding box is extended onto the neighboring face
  55766. // depends on which edge of neighboring face abuts with this one
  55767. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  55768. case PMREMGenerator.CP_EDGE_LEFT:
  55769. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  55770. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55771. break;
  55772. case PMREMGenerator.CP_EDGE_RIGHT:
  55773. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  55774. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55775. break;
  55776. case PMREMGenerator.CP_EDGE_TOP:
  55777. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  55778. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  55779. break;
  55780. case PMREMGenerator.CP_EDGE_BOTTOM:
  55781. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  55782. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  55783. break;
  55784. }
  55785. //clamp filter extents in non-center tap faces to remain within surface
  55786. filterExtents[neighborFace].clampMin(0, 0, 0);
  55787. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  55788. }
  55789. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  55790. // from the center tap face, then process the opposite face entirely for now.
  55791. //Note that the cases in which this happens, what usually happens is that
  55792. // more than one edge bleeds onto the opposite face, and the bounding box
  55793. // encompasses the entire cube map face.
  55794. if (bleedOverAmount[i] > srcSize) {
  55795. //determine opposite face
  55796. switch (faceIdx) {
  55797. case PMREMGenerator.CP_FACE_X_POS:
  55798. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55799. break;
  55800. case PMREMGenerator.CP_FACE_X_NEG:
  55801. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  55802. break;
  55803. case PMREMGenerator.CP_FACE_Y_POS:
  55804. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55805. break;
  55806. case PMREMGenerator.CP_FACE_Y_NEG:
  55807. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55808. break;
  55809. case PMREMGenerator.CP_FACE_Z_POS:
  55810. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55811. break;
  55812. case PMREMGenerator.CP_FACE_Z_NEG:
  55813. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55814. break;
  55815. default:
  55816. break;
  55817. }
  55818. //just encompass entire face for now
  55819. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  55820. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  55821. }
  55822. }
  55823. };
  55824. //--------------------------------------------------------------------------------------
  55825. //ProcessFilterExtents
  55826. // Process bounding box in each cube face
  55827. //
  55828. //--------------------------------------------------------------------------------------
  55829. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  55830. //accumulators are 64-bit floats in order to have the precision needed
  55831. // over a summation of a large number of pixels
  55832. var dstAccum = [0, 0, 0, 0];
  55833. var weightAccum = 0;
  55834. var k = 0;
  55835. var nSrcChannels = this.numChannels;
  55836. // norm cube map and srcCubeMap have same face width
  55837. var faceWidth = srcSize;
  55838. //amount to add to pointer to move to next scanline in images
  55839. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  55840. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  55841. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  55842. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  55843. // iterate over cubefaces
  55844. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  55845. //if bbox is non empty
  55846. if (!filterExtents[iFaceIdx].empty()) {
  55847. var uStart = filterExtents[iFaceIdx].min.x;
  55848. var vStart = filterExtents[iFaceIdx].min.y;
  55849. var uEnd = filterExtents[iFaceIdx].max.x;
  55850. var vEnd = filterExtents[iFaceIdx].max.y;
  55851. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  55852. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  55853. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  55854. for (var v = vStart; v <= vEnd; v++) {
  55855. var normCubeRowWalk = 0;
  55856. var srcCubeRowWalk = 0;
  55857. for (var u = uStart; u <= uEnd; u++) {
  55858. //pointer to direction in cube map associated with texel
  55859. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  55860. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  55861. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  55862. //check dot product to see if texel is within cone
  55863. var tapDotProd = texelVectX * centerTapDir.x +
  55864. texelVectY * centerTapDir.y +
  55865. texelVectZ * centerTapDir.z;
  55866. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  55867. //solid angle stored in 4th channel of normalizer/solid angle cube map
  55868. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  55869. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  55870. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  55871. // so just adding one to specularpower do the trick.
  55872. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  55873. //iterate over channels
  55874. for (k = 0; k < nSrcChannels; k++) {
  55875. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  55876. srcCubeRowWalk++;
  55877. }
  55878. weightAccum += weight; //accumulate weight
  55879. }
  55880. else {
  55881. //step across source pixel
  55882. srcCubeRowWalk += nSrcChannels;
  55883. }
  55884. normCubeRowWalk += 4; // 4 channels per norm cube map.
  55885. }
  55886. startIndexNormCubeMap += normCubePitch;
  55887. startIndexSrcCubeMap += srcCubePitch;
  55888. }
  55889. }
  55890. }
  55891. //divide through by weights if weight is non zero
  55892. if (weightAccum != 0.0) {
  55893. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  55894. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  55895. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  55896. if (this.numChannels > 3) {
  55897. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  55898. }
  55899. }
  55900. else {
  55901. // otherwise sample nearest
  55902. // get face idx and u, v texel coordinate in face
  55903. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  55904. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  55905. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  55906. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  55907. if (this.numChannels > 3) {
  55908. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  55909. }
  55910. }
  55911. return PMREMGenerator._vectorTemp;
  55912. };
  55913. //--------------------------------------------------------------------------------------
  55914. // Fixup cube edges
  55915. //
  55916. // average texels on cube map faces across the edges
  55917. // WARP/BENT Method Only.
  55918. //--------------------------------------------------------------------------------------
  55919. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  55920. var k;
  55921. var j;
  55922. var i;
  55923. var iFace;
  55924. var iCorner = 0;
  55925. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  55926. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  55927. // note that if functionality to filter across the three texels for each corner, then
  55928. //indexed by corner and face idx. the array contains the face the start points belongs to.
  55929. var cornerPtr = [
  55930. [[], [], []],
  55931. [[], [], []],
  55932. [[], [], []],
  55933. [[], [], []],
  55934. [[], [], []],
  55935. [[], [], []],
  55936. [[], [], []],
  55937. [[], [], []]
  55938. ];
  55939. //if there is no fixup, or fixup width = 0, do nothing
  55940. if (cubeMapSize < 1) {
  55941. return;
  55942. }
  55943. //special case 1x1 cubemap, average face colors
  55944. if (cubeMapSize == 1) {
  55945. //iterate over channels
  55946. for (k = 0; k < this.numChannels; k++) {
  55947. var accum = 0.0;
  55948. //iterate over faces to accumulate face colors
  55949. for (iFace = 0; iFace < 6; iFace++) {
  55950. accum += cubeMap[iFace][k];
  55951. }
  55952. //compute average over 6 face colors
  55953. accum /= 6.0;
  55954. //iterate over faces to distribute face colors
  55955. for (iFace = 0; iFace < 6; iFace++) {
  55956. cubeMap[iFace][k] = accum;
  55957. }
  55958. }
  55959. return;
  55960. }
  55961. //iterate over faces to collect list of corner texel pointers
  55962. for (iFace = 0; iFace < 6; iFace++) {
  55963. //the 4 corner pointers for this face
  55964. faceCornerStartIndicies[0] = [iFace, 0];
  55965. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  55966. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  55967. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  55968. //iterate over face corners to collect cube corner pointers
  55969. for (iCorner = 0; iCorner < 4; iCorner++) {
  55970. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  55971. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  55972. cornerNumPtrs[corner]++;
  55973. }
  55974. }
  55975. //iterate over corners to average across corner tap values
  55976. for (iCorner = 0; iCorner < 8; iCorner++) {
  55977. for (k = 0; k < this.numChannels; k++) {
  55978. var cornerTapAccum = 0.0;
  55979. //iterate over corner texels and average results
  55980. for (i = 0; i < 3; i++) {
  55981. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  55982. }
  55983. //divide by 3 to compute average of corner tap values
  55984. cornerTapAccum *= (1.0 / 3.0);
  55985. //iterate over corner texels and average results
  55986. for (i = 0; i < 3; i++) {
  55987. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  55988. }
  55989. }
  55990. }
  55991. //iterate over the twelve edges of the cube to average across edges
  55992. for (i = 0; i < 12; i++) {
  55993. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  55994. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  55995. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  55996. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  55997. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  55998. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  55999. var edgeWalk = 0;
  56000. var neighborEdgeWalk = 0;
  56001. //Determine walking pointers based on edge type
  56002. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  56003. switch (edge) {
  56004. case PMREMGenerator.CP_EDGE_LEFT:
  56005. // no change to faceEdgeStartPtr
  56006. edgeWalk = this.numChannels * cubeMapSize;
  56007. break;
  56008. case PMREMGenerator.CP_EDGE_RIGHT:
  56009. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56010. edgeWalk = this.numChannels * cubeMapSize;
  56011. break;
  56012. case PMREMGenerator.CP_EDGE_TOP:
  56013. // no change to faceEdgeStartPtr
  56014. edgeWalk = this.numChannels;
  56015. break;
  56016. case PMREMGenerator.CP_EDGE_BOTTOM:
  56017. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56018. edgeWalk = this.numChannels;
  56019. break;
  56020. }
  56021. //For certain types of edge abutments, the neighbor edge walk needs to
  56022. // be flipped: the cases are
  56023. // if a left edge mates with a left or bottom edge on the neighbor
  56024. // if a top edge mates with a top or right edge on the neighbor
  56025. // if a right edge mates with a right or top edge on the neighbor
  56026. // if a bottom edge mates with a bottom or left edge on the neighbor
  56027. //Seeing as the edges are enumerated as follows
  56028. // left =0
  56029. // right =1
  56030. // top =2
  56031. // bottom =3
  56032. //
  56033. //If the edge enums are the same, or the sum of the enums == 3,
  56034. // the neighbor edge walk needs to be flipped
  56035. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  56036. switch (neighborEdge) {
  56037. case PMREMGenerator.CP_EDGE_LEFT:
  56038. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  56039. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56040. break;
  56041. case PMREMGenerator.CP_EDGE_RIGHT:
  56042. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56043. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56044. break;
  56045. case PMREMGenerator.CP_EDGE_TOP:
  56046. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56047. neighborEdgeWalk = -this.numChannels;
  56048. break;
  56049. case PMREMGenerator.CP_EDGE_BOTTOM:
  56050. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56051. neighborEdgeWalk = -this.numChannels;
  56052. break;
  56053. }
  56054. }
  56055. else {
  56056. //swapped direction neighbor edge walk
  56057. switch (neighborEdge) {
  56058. case PMREMGenerator.CP_EDGE_LEFT:
  56059. //no change to neighborEdgeStartPtr for this case since it points
  56060. // to the upper left corner already
  56061. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56062. break;
  56063. case PMREMGenerator.CP_EDGE_RIGHT:
  56064. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56065. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56066. break;
  56067. case PMREMGenerator.CP_EDGE_TOP:
  56068. //no change to neighborEdgeStartPtr for this case since it points
  56069. // to the upper left corner already
  56070. neighborEdgeWalk = this.numChannels;
  56071. break;
  56072. case PMREMGenerator.CP_EDGE_BOTTOM:
  56073. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56074. neighborEdgeWalk = this.numChannels;
  56075. break;
  56076. }
  56077. }
  56078. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  56079. //nearby neighborhood
  56080. //step ahead one texel on edge
  56081. edgeStartIndex += edgeWalk;
  56082. neighborEdgeStartIndex += neighborEdgeWalk;
  56083. // note that this loop does not process the corner texels, since they have already been
  56084. // averaged across faces across earlier
  56085. for (j = 1; j < (cubeMapSize - 1); j++) {
  56086. //for each set of taps along edge, average them
  56087. // and rewrite the results into the edges
  56088. for (k = 0; k < this.numChannels; k++) {
  56089. var edgeTap = cubeMap[face][edgeStartIndex + k];
  56090. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  56091. //compute average of tap intensity values
  56092. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  56093. //propagate average of taps to edge taps
  56094. cubeMap[face][edgeStartIndex + k] = avgTap;
  56095. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  56096. }
  56097. edgeStartIndex += edgeWalk;
  56098. neighborEdgeStartIndex += neighborEdgeWalk;
  56099. }
  56100. }
  56101. };
  56102. return PMREMGenerator;
  56103. }());
  56104. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  56105. PMREMGenerator.CP_UDIR = 0;
  56106. PMREMGenerator.CP_VDIR = 1;
  56107. PMREMGenerator.CP_FACEAXIS = 2;
  56108. //used to index cube faces
  56109. PMREMGenerator.CP_FACE_X_POS = 0;
  56110. PMREMGenerator.CP_FACE_X_NEG = 1;
  56111. PMREMGenerator.CP_FACE_Y_POS = 2;
  56112. PMREMGenerator.CP_FACE_Y_NEG = 3;
  56113. PMREMGenerator.CP_FACE_Z_POS = 4;
  56114. PMREMGenerator.CP_FACE_Z_NEG = 5;
  56115. //used to index image edges
  56116. // NOTE.. the actual number corresponding to the edge is important
  56117. // do not change these, or the code will break
  56118. //
  56119. // CP_EDGE_LEFT is u = 0
  56120. // CP_EDGE_RIGHT is u = width-1
  56121. // CP_EDGE_TOP is v = 0
  56122. // CP_EDGE_BOTTOM is v = height-1
  56123. PMREMGenerator.CP_EDGE_LEFT = 0;
  56124. PMREMGenerator.CP_EDGE_RIGHT = 1;
  56125. PMREMGenerator.CP_EDGE_TOP = 2;
  56126. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  56127. //corners of CUBE map (P or N specifys if it corresponds to the
  56128. // positive or negative direction each of X, Y, and Z
  56129. PMREMGenerator.CP_CORNER_NNN = 0;
  56130. PMREMGenerator.CP_CORNER_NNP = 1;
  56131. PMREMGenerator.CP_CORNER_NPN = 2;
  56132. PMREMGenerator.CP_CORNER_NPP = 3;
  56133. PMREMGenerator.CP_CORNER_PNN = 4;
  56134. PMREMGenerator.CP_CORNER_PNP = 5;
  56135. PMREMGenerator.CP_CORNER_PPN = 6;
  56136. PMREMGenerator.CP_CORNER_PPP = 7;
  56137. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  56138. //3x2 matrices that map cube map indexing vectors in 3d
  56139. // (after face selection and divide through by the
  56140. // _ABSOLUTE VALUE_ of the max coord)
  56141. // into NVC space
  56142. //Note this currently assumes the D3D cube face ordering and orientation
  56143. PMREMGenerator._sgFace2DMapping = [
  56144. //XPOS face
  56145. [[0, 0, -1],
  56146. [0, -1, 0],
  56147. [1, 0, 0]],
  56148. //XNEG face
  56149. [[0, 0, 1],
  56150. [0, -1, 0],
  56151. [-1, 0, 0]],
  56152. //YPOS face
  56153. [[1, 0, 0],
  56154. [0, 0, 1],
  56155. [0, 1, 0]],
  56156. //YNEG face
  56157. [[1, 0, 0],
  56158. [0, 0, -1],
  56159. [0, -1, 0]],
  56160. //ZPOS face
  56161. [[1, 0, 0],
  56162. [0, -1, 0],
  56163. [0, 0, 1]],
  56164. //ZNEG face
  56165. [[-1, 0, 0],
  56166. [0, -1, 0],
  56167. [0, 0, -1]],
  56168. ];
  56169. //------------------------------------------------------------------------------
  56170. // D3D cube map face specification
  56171. // mapping from 3D x,y,z cube map lookup coordinates
  56172. // to 2D within face u,v coordinates
  56173. //
  56174. // --------------------> U direction
  56175. // | (within-face texture space)
  56176. // | _____
  56177. // | | |
  56178. // | | +Y |
  56179. // | _____|_____|_____ _____
  56180. // | | | | | |
  56181. // | | -X | +Z | +X | -Z |
  56182. // | |_____|_____|_____|_____|
  56183. // | | |
  56184. // | | -Y |
  56185. // | |_____|
  56186. // |
  56187. // v V direction
  56188. // (within-face texture space)
  56189. //------------------------------------------------------------------------------
  56190. //Information about neighbors and how texture coorrdinates change across faces
  56191. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  56192. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  56193. //Note this currently assumes the D3D cube face ordering and orientation
  56194. PMREMGenerator._sgCubeNgh = [
  56195. //XPOS face
  56196. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56197. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56198. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56199. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  56200. //XNEG face
  56201. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56202. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  56203. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  56204. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  56205. //YPOS face
  56206. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56207. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56208. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56209. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  56210. //YNEG face
  56211. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56212. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56213. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56214. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  56215. //ZPOS face
  56216. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56217. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56218. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56219. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  56220. //ZNEG face
  56221. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56222. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56223. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  56224. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  56225. ];
  56226. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  56227. // this table is used to average over the edges.
  56228. PMREMGenerator._sgCubeEdgeList = [
  56229. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56230. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56231. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56232. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56233. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56234. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56235. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56236. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56237. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  56238. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56239. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56240. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  56241. ];
  56242. //Information about which of the 8 cube corners are correspond to the
  56243. // the 4 corners in each cube face
  56244. // the order is upper left, upper right, lower left, lower right
  56245. PMREMGenerator._sgCubeCornerList = [
  56246. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  56247. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  56248. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  56249. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  56250. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  56251. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  56252. ];
  56253. Internals.PMREMGenerator = PMREMGenerator;
  56254. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56255. })(BABYLON || (BABYLON = {}));
  56256. //# sourceMappingURL=babylon.pmremgenerator.js.map
  56257. var BABYLON;
  56258. (function (BABYLON) {
  56259. /**
  56260. * This represents a texture coming from an HDR input.
  56261. *
  56262. * The only supported format is currently panorama picture stored in RGBE format.
  56263. * Example of such files can be found on HDRLib: http://hdrlib.com/
  56264. */
  56265. var HDRCubeTexture = (function (_super) {
  56266. __extends(HDRCubeTexture, _super);
  56267. /**
  56268. * Instantiates an HDRTexture from the following parameters.
  56269. *
  56270. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  56271. * @param scene The scene the texture will be used in
  56272. * @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.
  56273. * @param noMipmap Forces to not generate the mipmap if true
  56274. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  56275. * @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)
  56276. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  56277. */
  56278. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  56279. if (noMipmap === void 0) { noMipmap = false; }
  56280. if (generateHarmonics === void 0) { generateHarmonics = true; }
  56281. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  56282. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  56283. if (onLoad === void 0) { onLoad = null; }
  56284. if (onError === void 0) { onError = null; }
  56285. var _this = _super.call(this, scene) || this;
  56286. _this._useInGammaSpace = false;
  56287. _this._generateHarmonics = true;
  56288. _this._isBABYLONPreprocessed = false;
  56289. _this._onLoad = null;
  56290. _this._onError = null;
  56291. /**
  56292. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  56293. */
  56294. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56295. /**
  56296. * The spherical polynomial data extracted from the texture.
  56297. */
  56298. _this.sphericalPolynomial = null;
  56299. /**
  56300. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  56301. * This is usefull at run time to apply the good shader.
  56302. */
  56303. _this.isPMREM = false;
  56304. _this._isBlocking = true;
  56305. if (!url) {
  56306. return _this;
  56307. }
  56308. _this.name = url;
  56309. _this.url = url;
  56310. _this.hasAlpha = false;
  56311. _this.isCube = true;
  56312. _this._textureMatrix = BABYLON.Matrix.Identity();
  56313. _this._onLoad = onLoad;
  56314. _this._onError = onError;
  56315. if (size) {
  56316. _this._isBABYLONPreprocessed = false;
  56317. _this._noMipmap = noMipmap;
  56318. _this._size = size;
  56319. _this._useInGammaSpace = useInGammaSpace;
  56320. _this._usePMREMGenerator = usePMREMGenerator &&
  56321. scene.getEngine().getCaps().textureLOD &&
  56322. _this.getScene().getEngine().getCaps().textureFloat &&
  56323. !_this._useInGammaSpace;
  56324. }
  56325. else {
  56326. _this._isBABYLONPreprocessed = true;
  56327. _this._noMipmap = false;
  56328. _this._useInGammaSpace = false;
  56329. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  56330. _this.getScene().getEngine().getCaps().textureFloat &&
  56331. !_this._useInGammaSpace;
  56332. }
  56333. _this.isPMREM = _this._usePMREMGenerator;
  56334. _this._texture = _this._getFromCache(url, _this._noMipmap);
  56335. if (!_this._texture) {
  56336. if (!scene.useDelayedTextureLoading) {
  56337. _this.loadTexture();
  56338. }
  56339. else {
  56340. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56341. }
  56342. }
  56343. return _this;
  56344. }
  56345. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  56346. /**
  56347. * Gets wether or not the texture is blocking during loading.
  56348. */
  56349. get: function () {
  56350. return this._isBlocking;
  56351. },
  56352. /**
  56353. * Sets wether or not the texture is blocking during loading.
  56354. */
  56355. set: function (value) {
  56356. this._isBlocking = value;
  56357. },
  56358. enumerable: true,
  56359. configurable: true
  56360. });
  56361. /**
  56362. * Occurs when the file is a preprocessed .babylon.hdr file.
  56363. */
  56364. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  56365. var _this = this;
  56366. var mipLevels = 0;
  56367. var floatArrayView = null;
  56368. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  56369. var mips = [];
  56370. var startIndex = 30;
  56371. for (var level = 0; level < mipLevels; level++) {
  56372. mips.push([]);
  56373. // Fill each pixel of the mip level.
  56374. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  56375. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56376. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  56377. mips[level].push(faceData);
  56378. startIndex += faceSize;
  56379. }
  56380. }
  56381. return mips;
  56382. } : null;
  56383. var callback = function (buffer) {
  56384. // Create Native Array Views
  56385. var intArrayView = new Int32Array(buffer);
  56386. floatArrayView = new Float32Array(buffer);
  56387. // Fill header.
  56388. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  56389. _this._size = intArrayView[1]; // CubeMap max mip face size.
  56390. // Update Texture Information.
  56391. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  56392. // Fill polynomial information.
  56393. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  56394. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  56395. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  56396. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  56397. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  56398. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  56399. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  56400. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  56401. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  56402. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  56403. // Fill pixel data.
  56404. mipLevels = intArrayView[29]; // Number of mip levels.
  56405. var startIndex = 30;
  56406. var data = [];
  56407. var faceSize = Math.pow(_this._size, 2) * 3;
  56408. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56409. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  56410. startIndex += faceSize;
  56411. }
  56412. var results = [];
  56413. var byteArray = null;
  56414. // Push each faces.
  56415. for (var k = 0; k < 6; k++) {
  56416. var dataFace = null;
  56417. // If special cases.
  56418. if (!mipmapGenerator) {
  56419. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  56420. dataFace = data[j];
  56421. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56422. // 3 channels of 1 bytes per pixel in bytes.
  56423. var byteBuffer = new ArrayBuffer(faceSize);
  56424. byteArray = new Uint8Array(byteBuffer);
  56425. }
  56426. for (var i = 0; i < _this._size * _this._size; i++) {
  56427. // Put in gamma space if requested.
  56428. if (_this._useInGammaSpace) {
  56429. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56430. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56431. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56432. }
  56433. // Convert to int texture for fallback.
  56434. if (byteArray) {
  56435. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56436. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56437. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56438. // May use luminance instead if the result is not accurate.
  56439. var max = Math.max(Math.max(r, g), b);
  56440. if (max > 255) {
  56441. var scale = 255 / max;
  56442. r *= scale;
  56443. g *= scale;
  56444. b *= scale;
  56445. }
  56446. byteArray[(i * 3) + 0] = r;
  56447. byteArray[(i * 3) + 1] = g;
  56448. byteArray[(i * 3) + 2] = b;
  56449. }
  56450. }
  56451. }
  56452. else {
  56453. dataFace = data[k];
  56454. }
  56455. // Fill the array accordingly.
  56456. if (byteArray) {
  56457. results.push(byteArray);
  56458. }
  56459. else {
  56460. results.push(dataFace);
  56461. }
  56462. }
  56463. return results;
  56464. };
  56465. 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);
  56466. };
  56467. /**
  56468. * Occurs when the file is raw .hdr file.
  56469. */
  56470. HDRCubeTexture.prototype.loadHDRTexture = function () {
  56471. var _this = this;
  56472. var callback = function (buffer) {
  56473. // Extract the raw linear data.
  56474. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  56475. // Generate harmonics if needed.
  56476. if (_this._generateHarmonics) {
  56477. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  56478. }
  56479. var results = [];
  56480. var byteArray = null;
  56481. // Push each faces.
  56482. for (var j = 0; j < 6; j++) {
  56483. // Create uintarray fallback.
  56484. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56485. // 3 channels of 1 bytes per pixel in bytes.
  56486. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  56487. byteArray = new Uint8Array(byteBuffer);
  56488. }
  56489. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  56490. // If special cases.
  56491. if (_this._useInGammaSpace || byteArray) {
  56492. for (var i = 0; i < _this._size * _this._size; i++) {
  56493. // Put in gamma space if requested.
  56494. if (_this._useInGammaSpace) {
  56495. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56496. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56497. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56498. }
  56499. // Convert to int texture for fallback.
  56500. if (byteArray) {
  56501. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56502. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56503. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56504. // May use luminance instead if the result is not accurate.
  56505. var max = Math.max(Math.max(r, g), b);
  56506. if (max > 255) {
  56507. var scale = 255 / max;
  56508. r *= scale;
  56509. g *= scale;
  56510. b *= scale;
  56511. }
  56512. byteArray[(i * 3) + 0] = r;
  56513. byteArray[(i * 3) + 1] = g;
  56514. byteArray[(i * 3) + 2] = b;
  56515. }
  56516. }
  56517. }
  56518. if (byteArray) {
  56519. results.push(byteArray);
  56520. }
  56521. else {
  56522. results.push(dataFace);
  56523. }
  56524. }
  56525. return results;
  56526. };
  56527. var mipmapGenerator = null;
  56528. if (!this._noMipmap &&
  56529. this._usePMREMGenerator) {
  56530. mipmapGenerator = function (data) {
  56531. // Custom setup of the generator matching with the PBR shader values.
  56532. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  56533. return generator.filterCubeMap();
  56534. };
  56535. }
  56536. 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);
  56537. };
  56538. /**
  56539. * Starts the loading process of the texture.
  56540. */
  56541. HDRCubeTexture.prototype.loadTexture = function () {
  56542. if (this._isBABYLONPreprocessed) {
  56543. this.loadBabylonTexture();
  56544. }
  56545. else {
  56546. this.loadHDRTexture();
  56547. }
  56548. };
  56549. HDRCubeTexture.prototype.clone = function () {
  56550. var size = this._isBABYLONPreprocessed ? null : this._size;
  56551. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  56552. // Base texture
  56553. newTexture.level = this.level;
  56554. newTexture.wrapU = this.wrapU;
  56555. newTexture.wrapV = this.wrapV;
  56556. newTexture.coordinatesIndex = this.coordinatesIndex;
  56557. newTexture.coordinatesMode = this.coordinatesMode;
  56558. return newTexture;
  56559. };
  56560. // Methods
  56561. HDRCubeTexture.prototype.delayLoad = function () {
  56562. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56563. return;
  56564. }
  56565. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56566. this._texture = this._getFromCache(this.url, this._noMipmap);
  56567. if (!this._texture) {
  56568. this.loadTexture();
  56569. }
  56570. };
  56571. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  56572. return this._textureMatrix;
  56573. };
  56574. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56575. var texture = null;
  56576. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56577. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  56578. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  56579. texture.name = parsedTexture.name;
  56580. texture.hasAlpha = parsedTexture.hasAlpha;
  56581. texture.level = parsedTexture.level;
  56582. texture.coordinatesMode = parsedTexture.coordinatesMode;
  56583. texture.isBlocking = parsedTexture.isBlocking;
  56584. }
  56585. return texture;
  56586. };
  56587. HDRCubeTexture.prototype.serialize = function () {
  56588. if (!this.name) {
  56589. return null;
  56590. }
  56591. var serializationObject = {};
  56592. serializationObject.name = this.name;
  56593. serializationObject.hasAlpha = this.hasAlpha;
  56594. serializationObject.isCube = true;
  56595. serializationObject.level = this.level;
  56596. serializationObject.size = this._size;
  56597. serializationObject.coordinatesMode = this.coordinatesMode;
  56598. serializationObject.useInGammaSpace = this._useInGammaSpace;
  56599. serializationObject.generateHarmonics = this._generateHarmonics;
  56600. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  56601. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  56602. serializationObject.customType = "BABYLON.HDRCubeTexture";
  56603. serializationObject.noMipmap = this._noMipmap;
  56604. serializationObject.isBlocking = this._isBlocking;
  56605. return serializationObject;
  56606. };
  56607. /**
  56608. * Saves as a file the data contained in the texture in a binary format.
  56609. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56610. * as the spherical used in the lighting.
  56611. * @param url The HDR file url.
  56612. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56613. * @param onError Method called if any error happens during download.
  56614. * @return The packed binary data.
  56615. */
  56616. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  56617. if (onError === void 0) { onError = null; }
  56618. var callback = function (buffer) {
  56619. var data = new Blob([buffer], { type: 'application/octet-stream' });
  56620. // Returns a URL you can use as a href.
  56621. var objUrl = window.URL.createObjectURL(data);
  56622. // Simulates a link to it and click to dowload.
  56623. var a = document.createElement("a");
  56624. document.body.appendChild(a);
  56625. a.style.display = "none";
  56626. a.href = objUrl;
  56627. a.download = "envmap.babylon.hdr";
  56628. a.click();
  56629. };
  56630. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  56631. };
  56632. /**
  56633. * Serializes the data contained in the texture in a binary format.
  56634. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56635. * as the spherical used in the lighting.
  56636. * @param url The HDR file url.
  56637. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56638. * @param onError Method called if any error happens during download.
  56639. * @return The packed binary data.
  56640. */
  56641. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  56642. if (onError === void 0) { onError = null; }
  56643. // Needs the url tho create the texture.
  56644. if (!url) {
  56645. return null;
  56646. }
  56647. // Check Power of two size.
  56648. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  56649. return null;
  56650. }
  56651. var getDataCallback = function (dataBuffer) {
  56652. // Extract the raw linear data.
  56653. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  56654. // Generate harmonics if needed.
  56655. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  56656. // Generate seamless faces
  56657. var mipGeneratorArray = [];
  56658. // Data are known to be in +X +Y +Z -X -Y -Z
  56659. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  56660. mipGeneratorArray.push(cubeData.right); // +X
  56661. mipGeneratorArray.push(cubeData.left); // -X
  56662. mipGeneratorArray.push(cubeData.up); // +Y
  56663. mipGeneratorArray.push(cubeData.down); // -Y
  56664. mipGeneratorArray.push(cubeData.front); // +Z
  56665. mipGeneratorArray.push(cubeData.back); // -Z
  56666. // Custom setup of the generator matching with the PBR shader values.
  56667. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  56668. var mippedData = generator.filterCubeMap();
  56669. // Compute required byte length.
  56670. var byteLength = 1 * 4; // Raw Data Version int32.
  56671. byteLength += 4; // CubeMap max mip face size int32.
  56672. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  56673. // Add data size.
  56674. byteLength += 4; // Number of mip levels int32.
  56675. for (var level = 0; level < mippedData.length; level++) {
  56676. var mipSize = size >> level;
  56677. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  56678. }
  56679. // Prepare binary structure.
  56680. var buffer = new ArrayBuffer(byteLength);
  56681. var intArrayView = new Int32Array(buffer);
  56682. var floatArrayView = new Float32Array(buffer);
  56683. // Fill header.
  56684. intArrayView[0] = 1; // Version 1.
  56685. intArrayView[1] = size; // CubeMap max mip face size.
  56686. // Fill polynomial information.
  56687. sphericalPolynomial.x.toArray(floatArrayView, 2);
  56688. sphericalPolynomial.y.toArray(floatArrayView, 5);
  56689. sphericalPolynomial.z.toArray(floatArrayView, 8);
  56690. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  56691. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  56692. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  56693. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  56694. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  56695. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  56696. // Fill pixel data.
  56697. intArrayView[29] = mippedData.length; // Number of mip levels.
  56698. var startIndex = 30;
  56699. for (var level = 0; level < mippedData.length; level++) {
  56700. // Fill each pixel of the mip level.
  56701. var faceSize = Math.pow(size >> level, 2) * 3;
  56702. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56703. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  56704. startIndex += faceSize;
  56705. }
  56706. }
  56707. // Callback.
  56708. callback(buffer);
  56709. };
  56710. // Download and process.
  56711. BABYLON.Tools.LoadFile(url, function (data) {
  56712. getDataCallback(data);
  56713. }, null, null, true, onError);
  56714. };
  56715. return HDRCubeTexture;
  56716. }(BABYLON.BaseTexture));
  56717. HDRCubeTexture._facesMapping = [
  56718. "right",
  56719. "up",
  56720. "front",
  56721. "left",
  56722. "down",
  56723. "back"
  56724. ];
  56725. BABYLON.HDRCubeTexture = HDRCubeTexture;
  56726. })(BABYLON || (BABYLON = {}));
  56727. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  56728. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  56729. // Huge respect for a such great lib.
  56730. // Earcut license:
  56731. // Copyright (c) 2016, Mapbox
  56732. //
  56733. // Permission to use, copy, modify, and/or distribute this software for any purpose
  56734. // with or without fee is hereby granted, provided that the above copyright notice
  56735. // and this permission notice appear in all copies.
  56736. //
  56737. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  56738. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  56739. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  56740. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  56741. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  56742. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  56743. // THIS SOFTWARE.
  56744. var Earcut;
  56745. (function (Earcut) {
  56746. /**
  56747. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  56748. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  56749. * @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).
  56750. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  56751. */
  56752. function earcut(data, holeIndices, dim) {
  56753. dim = dim || 2;
  56754. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  56755. if (!outerNode)
  56756. return triangles;
  56757. var minX, minY, maxX, maxY, x, y, size;
  56758. if (hasHoles)
  56759. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  56760. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  56761. if (data.length > 80 * dim) {
  56762. minX = maxX = data[0];
  56763. minY = maxY = data[1];
  56764. for (var i = dim; i < outerLen; i += dim) {
  56765. x = data[i];
  56766. y = data[i + 1];
  56767. if (x < minX)
  56768. minX = x;
  56769. if (y < minY)
  56770. minY = y;
  56771. if (x > maxX)
  56772. maxX = x;
  56773. if (y > maxY)
  56774. maxY = y;
  56775. }
  56776. // minX, minY and size are later used to transform coords into integers for z-order calculation
  56777. size = Math.max(maxX - minX, maxY - minY);
  56778. }
  56779. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  56780. return triangles;
  56781. }
  56782. Earcut.earcut = earcut;
  56783. // create a circular doubly linked list from polygon points in the specified winding order
  56784. function linkedList(data, start, end, dim, clockwise) {
  56785. var i, last;
  56786. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  56787. for (i = start; i < end; i += dim)
  56788. last = insertNode(i, data[i], data[i + 1], last);
  56789. }
  56790. else {
  56791. for (i = end - dim; i >= start; i -= dim)
  56792. last = insertNode(i, data[i], data[i + 1], last);
  56793. }
  56794. if (last && equals(last, last.next)) {
  56795. removeNode(last);
  56796. last = last.next;
  56797. }
  56798. return last;
  56799. }
  56800. // eliminate colinear or duplicate points
  56801. function filterPoints(start, end) {
  56802. if (!start)
  56803. return start;
  56804. if (!end)
  56805. end = start;
  56806. var p = start, again;
  56807. do {
  56808. again = false;
  56809. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  56810. removeNode(p);
  56811. p = end = p.prev;
  56812. if (p === p.next)
  56813. return null;
  56814. again = true;
  56815. }
  56816. else {
  56817. p = p.next;
  56818. }
  56819. } while (again || p !== end);
  56820. return end;
  56821. }
  56822. // main ear slicing loop which triangulates a polygon (given as a linked list)
  56823. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  56824. if (!ear)
  56825. return;
  56826. // interlink polygon nodes in z-order
  56827. if (!pass && size)
  56828. indexCurve(ear, minX, minY, size);
  56829. var stop = ear, prev, next;
  56830. // iterate through ears, slicing them one by one
  56831. while (ear.prev !== ear.next) {
  56832. prev = ear.prev;
  56833. next = ear.next;
  56834. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  56835. // cut off the triangle
  56836. triangles.push(prev.i / dim);
  56837. triangles.push(ear.i / dim);
  56838. triangles.push(next.i / dim);
  56839. removeNode(ear);
  56840. // skipping the next vertice leads to less sliver triangles
  56841. ear = next.next;
  56842. stop = next.next;
  56843. continue;
  56844. }
  56845. ear = next;
  56846. // if we looped through the whole remaining polygon and can't find any more ears
  56847. if (ear === stop) {
  56848. // try filtering points and slicing again
  56849. if (!pass) {
  56850. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  56851. // if this didn't work, try curing all small self-intersections locally
  56852. }
  56853. else if (pass === 1) {
  56854. ear = cureLocalIntersections(ear, triangles, dim);
  56855. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  56856. // as a last resort, try splitting the remaining polygon into two
  56857. }
  56858. else if (pass === 2) {
  56859. splitEarcut(ear, triangles, dim, minX, minY, size);
  56860. }
  56861. break;
  56862. }
  56863. }
  56864. }
  56865. // check whether a polygon node forms a valid ear with adjacent nodes
  56866. function isEar(ear) {
  56867. var a = ear.prev, b = ear, c = ear.next;
  56868. if (area(a, b, c) >= 0)
  56869. return false; // reflex, can't be an ear
  56870. // now make sure we don't have other points inside the potential ear
  56871. var p = ear.next.next;
  56872. while (p !== ear.prev) {
  56873. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  56874. area(p.prev, p, p.next) >= 0)
  56875. return false;
  56876. p = p.next;
  56877. }
  56878. return true;
  56879. }
  56880. function isEarHashed(ear, minX, minY, size) {
  56881. var a = ear.prev, b = ear, c = ear.next;
  56882. if (area(a, b, c) >= 0)
  56883. return false; // reflex, can't be an ear
  56884. // triangle bbox; min & max are calculated like this for speed
  56885. 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);
  56886. // z-order range for the current triangle bbox;
  56887. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  56888. // first look for points inside the triangle in increasing z-order
  56889. var p = ear.nextZ;
  56890. while (p && p.z <= maxZ) {
  56891. if (p !== ear.prev &&
  56892. p !== ear.next &&
  56893. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  56894. area(p.prev, p, p.next) >= 0)
  56895. return false;
  56896. p = p.nextZ;
  56897. }
  56898. // then look for points in decreasing z-order
  56899. p = ear.prevZ;
  56900. while (p && p.z >= minZ) {
  56901. if (p !== ear.prev &&
  56902. p !== ear.next &&
  56903. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  56904. area(p.prev, p, p.next) >= 0)
  56905. return false;
  56906. p = p.prevZ;
  56907. }
  56908. return true;
  56909. }
  56910. // go through all polygon nodes and cure small local self-intersections
  56911. function cureLocalIntersections(start, triangles, dim) {
  56912. var p = start;
  56913. do {
  56914. var a = p.prev, b = p.next.next;
  56915. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  56916. triangles.push(a.i / dim);
  56917. triangles.push(p.i / dim);
  56918. triangles.push(b.i / dim);
  56919. // remove two nodes involved
  56920. removeNode(p);
  56921. removeNode(p.next);
  56922. p = start = b;
  56923. }
  56924. p = p.next;
  56925. } while (p !== start);
  56926. return p;
  56927. }
  56928. // try splitting polygon into two and triangulate them independently
  56929. function splitEarcut(start, triangles, dim, minX, minY, size) {
  56930. // look for a valid diagonal that divides the polygon into two
  56931. var a = start;
  56932. do {
  56933. var b = a.next.next;
  56934. while (b !== a.prev) {
  56935. if (a.i !== b.i && isValidDiagonal(a, b)) {
  56936. // split the polygon in two by the diagonal
  56937. var c = splitPolygon(a, b);
  56938. // filter colinear points around the cuts
  56939. a = filterPoints(a, a.next);
  56940. c = filterPoints(c, c.next);
  56941. // run earcut on each half
  56942. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  56943. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  56944. return;
  56945. }
  56946. b = b.next;
  56947. }
  56948. a = a.next;
  56949. } while (a !== start);
  56950. }
  56951. // link every hole into the outer loop, producing a single-ring polygon without holes
  56952. function eliminateHoles(data, holeIndices, outerNode, dim) {
  56953. var queue = [], i, len, start, end, list;
  56954. for (i = 0, len = holeIndices.length; i < len; i++) {
  56955. start = holeIndices[i] * dim;
  56956. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  56957. list = linkedList(data, start, end, dim, false);
  56958. if (list === list.next)
  56959. list.steiner = true;
  56960. queue.push(getLeftmost(list));
  56961. }
  56962. queue.sort(compareX);
  56963. // process holes from left to right
  56964. for (i = 0; i < queue.length; i++) {
  56965. eliminateHole(queue[i], outerNode);
  56966. outerNode = filterPoints(outerNode, outerNode.next);
  56967. }
  56968. return outerNode;
  56969. }
  56970. function compareX(a, b) {
  56971. return a.x - b.x;
  56972. }
  56973. // find a bridge between vertices that connects hole with an outer ring and and link it
  56974. function eliminateHole(hole, outerNode) {
  56975. outerNode = findHoleBridge(hole, outerNode);
  56976. if (outerNode) {
  56977. var b = splitPolygon(outerNode, hole);
  56978. filterPoints(b, b.next);
  56979. }
  56980. }
  56981. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  56982. function findHoleBridge(hole, outerNode) {
  56983. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  56984. // find a segment intersected by a ray from the hole's leftmost point to the left;
  56985. // segment's endpoint with lesser x will be potential connection point
  56986. do {
  56987. if (hy <= p.y && hy >= p.next.y) {
  56988. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  56989. if (x <= hx && x > qx) {
  56990. qx = x;
  56991. if (x === hx) {
  56992. if (hy === p.y)
  56993. return p;
  56994. if (hy === p.next.y)
  56995. return p.next;
  56996. }
  56997. m = p.x < p.next.x ? p : p.next;
  56998. }
  56999. }
  57000. p = p.next;
  57001. } while (p !== outerNode);
  57002. if (!m)
  57003. return null;
  57004. if (hx === qx)
  57005. return m.prev; // hole touches outer segment; pick lower endpoint
  57006. // look for points inside the triangle of hole point, segment intersection and endpoint;
  57007. // if there are no points found, we have a valid connection;
  57008. // otherwise choose the point of the minimum angle with the ray as connection point
  57009. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  57010. p = m.next;
  57011. while (p !== stop) {
  57012. if (hx >= p.x &&
  57013. p.x >= mx &&
  57014. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  57015. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  57016. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  57017. m = p;
  57018. tanMin = tan;
  57019. }
  57020. }
  57021. p = p.next;
  57022. }
  57023. return m;
  57024. }
  57025. // interlink polygon nodes in z-order
  57026. function indexCurve(start, minX, minY, size) {
  57027. var p = start;
  57028. do {
  57029. if (p.z === null)
  57030. p.z = zOrder(p.x, p.y, minX, minY, size);
  57031. p.prevZ = p.prev;
  57032. p.nextZ = p.next;
  57033. p = p.next;
  57034. } while (p !== start);
  57035. p.prevZ.nextZ = null;
  57036. p.prevZ = null;
  57037. sortLinked(p);
  57038. }
  57039. // Simon Tatham's linked list merge sort algorithm
  57040. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  57041. function sortLinked(list) {
  57042. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  57043. do {
  57044. p = list;
  57045. list = null;
  57046. tail = null;
  57047. numMerges = 0;
  57048. while (p) {
  57049. numMerges++;
  57050. q = p;
  57051. pSize = 0;
  57052. for (i = 0; i < inSize; i++) {
  57053. pSize++;
  57054. q = q.nextZ;
  57055. if (!q)
  57056. break;
  57057. }
  57058. qSize = inSize;
  57059. while (pSize > 0 || (qSize > 0 && q)) {
  57060. if (pSize === 0) {
  57061. e = q;
  57062. q = q.nextZ;
  57063. qSize--;
  57064. }
  57065. else if (qSize === 0 || !q) {
  57066. e = p;
  57067. p = p.nextZ;
  57068. pSize--;
  57069. }
  57070. else if (p.z <= q.z) {
  57071. e = p;
  57072. p = p.nextZ;
  57073. pSize--;
  57074. }
  57075. else {
  57076. e = q;
  57077. q = q.nextZ;
  57078. qSize--;
  57079. }
  57080. if (tail)
  57081. tail.nextZ = e;
  57082. else
  57083. list = e;
  57084. e.prevZ = tail;
  57085. tail = e;
  57086. }
  57087. p = q;
  57088. }
  57089. tail.nextZ = null;
  57090. inSize *= 2;
  57091. } while (numMerges > 1);
  57092. return list;
  57093. }
  57094. // z-order of a point given coords and size of the data bounding box
  57095. function zOrder(x, y, minX, minY, size) {
  57096. // coords are transformed into non-negative 15-bit integer range
  57097. x = 32767 * (x - minX) / size;
  57098. y = 32767 * (y - minY) / size;
  57099. x = (x | (x << 8)) & 0x00FF00FF;
  57100. x = (x | (x << 4)) & 0x0F0F0F0F;
  57101. x = (x | (x << 2)) & 0x33333333;
  57102. x = (x | (x << 1)) & 0x55555555;
  57103. y = (y | (y << 8)) & 0x00FF00FF;
  57104. y = (y | (y << 4)) & 0x0F0F0F0F;
  57105. y = (y | (y << 2)) & 0x33333333;
  57106. y = (y | (y << 1)) & 0x55555555;
  57107. return x | (y << 1);
  57108. }
  57109. // find the leftmost node of a polygon ring
  57110. function getLeftmost(start) {
  57111. var p = start, leftmost = start;
  57112. do {
  57113. if (p.x < leftmost.x)
  57114. leftmost = p;
  57115. p = p.next;
  57116. } while (p !== start);
  57117. return leftmost;
  57118. }
  57119. // check if a point lies within a convex triangle
  57120. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  57121. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  57122. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  57123. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  57124. }
  57125. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  57126. function isValidDiagonal(a, b) {
  57127. return a.next.i !== b.i &&
  57128. a.prev.i !== b.i &&
  57129. !intersectsPolygon(a, b) &&
  57130. locallyInside(a, b) &&
  57131. locallyInside(b, a) &&
  57132. middleInside(a, b);
  57133. }
  57134. // signed area of a triangle
  57135. function area(p, q, r) {
  57136. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  57137. }
  57138. // check if two points are equal
  57139. function equals(p1, p2) {
  57140. return p1.x === p2.x && p1.y === p2.y;
  57141. }
  57142. // check if two segments intersect
  57143. function intersects(p1, q1, p2, q2) {
  57144. if ((equals(p1, q1) && equals(p2, q2)) ||
  57145. (equals(p1, q2) && equals(p2, q1)))
  57146. return true;
  57147. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  57148. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  57149. }
  57150. // check if a polygon diagonal intersects any polygon segments
  57151. function intersectsPolygon(a, b) {
  57152. var p = a;
  57153. do {
  57154. if (p.i !== a.i &&
  57155. p.next.i !== a.i &&
  57156. p.i !== b.i &&
  57157. p.next.i !== b.i &&
  57158. intersects(p, p.next, a, b))
  57159. return true;
  57160. p = p.next;
  57161. } while (p !== a);
  57162. return false;
  57163. }
  57164. // check if a polygon diagonal is locally inside the polygon
  57165. function locallyInside(a, b) {
  57166. return area(a.prev, a, a.next) < 0
  57167. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  57168. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  57169. }
  57170. // check if the middle point of a polygon diagonal is inside the polygon
  57171. function middleInside(a, b) {
  57172. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  57173. do {
  57174. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  57175. inside = !inside;
  57176. p = p.next;
  57177. } while (p !== a);
  57178. return inside;
  57179. }
  57180. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  57181. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  57182. function splitPolygon(a, b) {
  57183. 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;
  57184. a.next = b;
  57185. b.prev = a;
  57186. a2.next = an;
  57187. an.prev = a2;
  57188. b2.next = a2;
  57189. a2.prev = b2;
  57190. bp.next = b2;
  57191. b2.prev = bp;
  57192. return b2;
  57193. }
  57194. // create a node and optionally link it with previous one (in a circular doubly linked list)
  57195. function insertNode(i, x, y, last) {
  57196. var p = new Node(i, x, y);
  57197. if (!last) {
  57198. p.prev = p;
  57199. p.next = p;
  57200. }
  57201. else {
  57202. p.next = last.next;
  57203. p.prev = last;
  57204. last.next.prev = p;
  57205. last.next = p;
  57206. }
  57207. return p;
  57208. }
  57209. function removeNode(p) {
  57210. p.next.prev = p.prev;
  57211. p.prev.next = p.next;
  57212. if (p.prevZ)
  57213. p.prevZ.nextZ = p.nextZ;
  57214. if (p.nextZ)
  57215. p.nextZ.prevZ = p.prevZ;
  57216. }
  57217. function Node(i, x, y) {
  57218. // vertice index in coordinates array
  57219. this.i = i;
  57220. // vertex coordinates
  57221. this.x = x;
  57222. this.y = y;
  57223. // previous and next vertice nodes in a polygon ring
  57224. this.prev = null;
  57225. this.next = null;
  57226. // z-order curve value
  57227. this.z = null;
  57228. // previous and next nodes in z-order
  57229. this.prevZ = null;
  57230. this.nextZ = null;
  57231. // indicates whether this is a steiner point
  57232. this.steiner = false;
  57233. }
  57234. /**
  57235. * return a percentage difference between the polygon area and its triangulation area;
  57236. * used to verify correctness of triangulation
  57237. */
  57238. function deviation(data, holeIndices, dim, triangles) {
  57239. var hasHoles = holeIndices && holeIndices.length;
  57240. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  57241. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  57242. if (hasHoles) {
  57243. for (var i = 0, len = holeIndices.length; i < len; i++) {
  57244. var start = holeIndices[i] * dim;
  57245. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  57246. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  57247. }
  57248. }
  57249. var trianglesArea = 0;
  57250. for (i = 0; i < triangles.length; i += 3) {
  57251. var a = triangles[i] * dim;
  57252. var b = triangles[i + 1] * dim;
  57253. var c = triangles[i + 2] * dim;
  57254. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  57255. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  57256. }
  57257. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  57258. }
  57259. Earcut.deviation = deviation;
  57260. ;
  57261. function signedArea(data, start, end, dim) {
  57262. var sum = 0;
  57263. for (var i = start, j = end - dim; i < end; i += dim) {
  57264. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  57265. j = i;
  57266. }
  57267. return sum;
  57268. }
  57269. /**
  57270. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  57271. */
  57272. function flatten(data) {
  57273. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  57274. for (var i = 0; i < data.length; i++) {
  57275. for (var j = 0; j < data[i].length; j++) {
  57276. for (var d = 0; d < dim; d++)
  57277. result.vertices.push(data[i][j][d]);
  57278. }
  57279. if (i > 0) {
  57280. holeIndex += data[i - 1].length;
  57281. result.holes.push(holeIndex);
  57282. }
  57283. }
  57284. return result;
  57285. }
  57286. Earcut.flatten = flatten;
  57287. ;
  57288. })(Earcut || (Earcut = {}));
  57289. //# sourceMappingURL=babylon.earcut.js.map
  57290. /// <reference path="..\Math\babylon.math.ts" />
  57291. var BABYLON;
  57292. (function (BABYLON) {
  57293. var IndexedVector2 = (function (_super) {
  57294. __extends(IndexedVector2, _super);
  57295. function IndexedVector2(original, index) {
  57296. var _this = _super.call(this, original.x, original.y) || this;
  57297. _this.index = index;
  57298. return _this;
  57299. }
  57300. return IndexedVector2;
  57301. }(BABYLON.Vector2));
  57302. var PolygonPoints = (function () {
  57303. function PolygonPoints() {
  57304. this.elements = new Array();
  57305. }
  57306. PolygonPoints.prototype.add = function (originalPoints) {
  57307. var _this = this;
  57308. var result = new Array();
  57309. originalPoints.forEach(function (point) {
  57310. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  57311. var newPoint = new IndexedVector2(point, _this.elements.length);
  57312. result.push(newPoint);
  57313. _this.elements.push(newPoint);
  57314. }
  57315. });
  57316. return result;
  57317. };
  57318. PolygonPoints.prototype.computeBounds = function () {
  57319. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  57320. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  57321. this.elements.forEach(function (point) {
  57322. // x
  57323. if (point.x < lmin.x) {
  57324. lmin.x = point.x;
  57325. }
  57326. else if (point.x > lmax.x) {
  57327. lmax.x = point.x;
  57328. }
  57329. // y
  57330. if (point.y < lmin.y) {
  57331. lmin.y = point.y;
  57332. }
  57333. else if (point.y > lmax.y) {
  57334. lmax.y = point.y;
  57335. }
  57336. });
  57337. return {
  57338. min: lmin,
  57339. max: lmax,
  57340. width: lmax.x - lmin.x,
  57341. height: lmax.y - lmin.y
  57342. };
  57343. };
  57344. return PolygonPoints;
  57345. }());
  57346. var Polygon = (function () {
  57347. function Polygon() {
  57348. }
  57349. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  57350. return [
  57351. new BABYLON.Vector2(xmin, ymin),
  57352. new BABYLON.Vector2(xmax, ymin),
  57353. new BABYLON.Vector2(xmax, ymax),
  57354. new BABYLON.Vector2(xmin, ymax)
  57355. ];
  57356. };
  57357. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  57358. if (cx === void 0) { cx = 0; }
  57359. if (cy === void 0) { cy = 0; }
  57360. if (numberOfSides === void 0) { numberOfSides = 32; }
  57361. var result = new Array();
  57362. var angle = 0;
  57363. var increment = (Math.PI * 2) / numberOfSides;
  57364. for (var i = 0; i < numberOfSides; i++) {
  57365. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  57366. angle -= increment;
  57367. }
  57368. return result;
  57369. };
  57370. Polygon.Parse = function (input) {
  57371. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  57372. var i, result = [];
  57373. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  57374. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  57375. }
  57376. return result;
  57377. };
  57378. Polygon.StartingAt = function (x, y) {
  57379. return BABYLON.Path2.StartingAt(x, y);
  57380. };
  57381. return Polygon;
  57382. }());
  57383. BABYLON.Polygon = Polygon;
  57384. var PolygonMeshBuilder = (function () {
  57385. function PolygonMeshBuilder(name, contours, scene) {
  57386. this._points = new PolygonPoints();
  57387. this._outlinepoints = new PolygonPoints();
  57388. this._holes = [];
  57389. this._epoints = new Array();
  57390. this._eholes = new Array();
  57391. this._name = name;
  57392. this._scene = scene;
  57393. var points;
  57394. if (contours instanceof BABYLON.Path2) {
  57395. points = contours.getPoints();
  57396. }
  57397. else {
  57398. points = contours;
  57399. }
  57400. this._addToepoint(points);
  57401. this._points.add(points);
  57402. this._outlinepoints.add(points);
  57403. }
  57404. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  57405. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  57406. var p = points_1[_i];
  57407. this._epoints.push(p.x, p.y);
  57408. }
  57409. };
  57410. PolygonMeshBuilder.prototype.addHole = function (hole) {
  57411. this._points.add(hole);
  57412. var holepoints = new PolygonPoints();
  57413. holepoints.add(hole);
  57414. this._holes.push(holepoints);
  57415. this._eholes.push(this._epoints.length / 2);
  57416. this._addToepoint(hole);
  57417. return this;
  57418. };
  57419. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  57420. var _this = this;
  57421. if (updatable === void 0) { updatable = false; }
  57422. var result = new BABYLON.Mesh(this._name, this._scene);
  57423. var normals = [];
  57424. var positions = [];
  57425. var uvs = [];
  57426. var bounds = this._points.computeBounds();
  57427. this._points.elements.forEach(function (p) {
  57428. normals.push(0, 1.0, 0);
  57429. positions.push(p.x, 0, p.y);
  57430. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  57431. });
  57432. var indices = [];
  57433. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  57434. for (var i = 0; i < res.length; i++) {
  57435. indices.push(res[i]);
  57436. }
  57437. if (depth > 0) {
  57438. var positionscount = (positions.length / 3); //get the current pointcount
  57439. this._points.elements.forEach(function (p) {
  57440. normals.push(0, -1.0, 0);
  57441. positions.push(p.x, -depth, p.y);
  57442. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  57443. });
  57444. var totalCount = indices.length;
  57445. for (var i = 0; i < totalCount; i += 3) {
  57446. var i0 = indices[i + 0];
  57447. var i1 = indices[i + 1];
  57448. var i2 = indices[i + 2];
  57449. indices.push(i2 + positionscount);
  57450. indices.push(i1 + positionscount);
  57451. indices.push(i0 + positionscount);
  57452. }
  57453. //Add the sides
  57454. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  57455. this._holes.forEach(function (hole) {
  57456. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  57457. });
  57458. }
  57459. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  57460. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  57461. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  57462. result.setIndices(indices);
  57463. return result;
  57464. };
  57465. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  57466. var StartIndex = positions.length / 3;
  57467. var ulength = 0;
  57468. for (var i = 0; i < points.elements.length; i++) {
  57469. var p = points.elements[i];
  57470. var p1;
  57471. if ((i + 1) > points.elements.length - 1) {
  57472. p1 = points.elements[0];
  57473. }
  57474. else {
  57475. p1 = points.elements[i + 1];
  57476. }
  57477. positions.push(p.x, 0, p.y);
  57478. positions.push(p.x, -depth, p.y);
  57479. positions.push(p1.x, 0, p1.y);
  57480. positions.push(p1.x, -depth, p1.y);
  57481. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  57482. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  57483. var v3 = v2.subtract(v1);
  57484. var v4 = new BABYLON.Vector3(0, 1, 0);
  57485. var vn = BABYLON.Vector3.Cross(v3, v4);
  57486. vn = vn.normalize();
  57487. uvs.push(ulength / bounds.width, 0);
  57488. uvs.push(ulength / bounds.width, 1);
  57489. ulength += v3.length();
  57490. uvs.push((ulength / bounds.width), 0);
  57491. uvs.push((ulength / bounds.width), 1);
  57492. if (!flip) {
  57493. normals.push(-vn.x, -vn.y, -vn.z);
  57494. normals.push(-vn.x, -vn.y, -vn.z);
  57495. normals.push(-vn.x, -vn.y, -vn.z);
  57496. normals.push(-vn.x, -vn.y, -vn.z);
  57497. indices.push(StartIndex);
  57498. indices.push(StartIndex + 1);
  57499. indices.push(StartIndex + 2);
  57500. indices.push(StartIndex + 1);
  57501. indices.push(StartIndex + 3);
  57502. indices.push(StartIndex + 2);
  57503. }
  57504. else {
  57505. normals.push(vn.x, vn.y, vn.z);
  57506. normals.push(vn.x, vn.y, vn.z);
  57507. normals.push(vn.x, vn.y, vn.z);
  57508. normals.push(vn.x, vn.y, vn.z);
  57509. indices.push(StartIndex);
  57510. indices.push(StartIndex + 2);
  57511. indices.push(StartIndex + 1);
  57512. indices.push(StartIndex + 1);
  57513. indices.push(StartIndex + 2);
  57514. indices.push(StartIndex + 3);
  57515. }
  57516. StartIndex += 4;
  57517. }
  57518. ;
  57519. };
  57520. return PolygonMeshBuilder;
  57521. }());
  57522. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  57523. })(BABYLON || (BABYLON = {}));
  57524. //# sourceMappingURL=babylon.polygonMesh.js.map
  57525. var BABYLON;
  57526. (function (BABYLON) {
  57527. // Unique ID when we import meshes from Babylon to CSG
  57528. var currentCSGMeshId = 0;
  57529. // # class Vertex
  57530. // Represents a vertex of a polygon. Use your own vertex class instead of this
  57531. // one to provide additional features like texture coordinates and vertex
  57532. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  57533. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  57534. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  57535. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  57536. // is not used anywhere else.
  57537. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  57538. var Vertex = (function () {
  57539. function Vertex(pos, normal, uv) {
  57540. this.pos = pos;
  57541. this.normal = normal;
  57542. this.uv = uv;
  57543. }
  57544. Vertex.prototype.clone = function () {
  57545. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  57546. };
  57547. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  57548. // orientation of a polygon is flipped.
  57549. Vertex.prototype.flip = function () {
  57550. this.normal = this.normal.scale(-1);
  57551. };
  57552. // Create a new vertex between this vertex and `other` by linearly
  57553. // interpolating all properties using a parameter of `t`. Subclasses should
  57554. // override this to interpolate additional properties.
  57555. Vertex.prototype.interpolate = function (other, t) {
  57556. 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));
  57557. };
  57558. return Vertex;
  57559. }());
  57560. // # class Plane
  57561. // Represents a plane in 3D space.
  57562. var Plane = (function () {
  57563. function Plane(normal, w) {
  57564. this.normal = normal;
  57565. this.w = w;
  57566. }
  57567. Plane.FromPoints = function (a, b, c) {
  57568. var v0 = c.subtract(a);
  57569. var v1 = b.subtract(a);
  57570. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  57571. return null;
  57572. }
  57573. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  57574. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  57575. };
  57576. Plane.prototype.clone = function () {
  57577. return new Plane(this.normal.clone(), this.w);
  57578. };
  57579. Plane.prototype.flip = function () {
  57580. this.normal.scaleInPlace(-1);
  57581. this.w = -this.w;
  57582. };
  57583. // Split `polygon` by this plane if needed, then put the polygon or polygon
  57584. // fragments in the appropriate lists. Coplanar polygons go into either
  57585. // `coplanarFront` or `coplanarBack` depending on their orientation with
  57586. // respect to this plane. Polygons in front or in back of this plane go into
  57587. // either `front` or `back`.
  57588. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  57589. var COPLANAR = 0;
  57590. var FRONT = 1;
  57591. var BACK = 2;
  57592. var SPANNING = 3;
  57593. // Classify each point as well as the entire polygon into one of the above
  57594. // four classes.
  57595. var polygonType = 0;
  57596. var types = [];
  57597. var i;
  57598. var t;
  57599. for (i = 0; i < polygon.vertices.length; i++) {
  57600. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  57601. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  57602. polygonType |= type;
  57603. types.push(type);
  57604. }
  57605. // Put the polygon in the correct list, splitting it when necessary.
  57606. switch (polygonType) {
  57607. case COPLANAR:
  57608. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  57609. break;
  57610. case FRONT:
  57611. front.push(polygon);
  57612. break;
  57613. case BACK:
  57614. back.push(polygon);
  57615. break;
  57616. case SPANNING:
  57617. var f = [], b = [];
  57618. for (i = 0; i < polygon.vertices.length; i++) {
  57619. var j = (i + 1) % polygon.vertices.length;
  57620. var ti = types[i], tj = types[j];
  57621. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  57622. if (ti !== BACK)
  57623. f.push(vi);
  57624. if (ti !== FRONT)
  57625. b.push(ti !== BACK ? vi.clone() : vi);
  57626. if ((ti | tj) === SPANNING) {
  57627. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  57628. var v = vi.interpolate(vj, t);
  57629. f.push(v);
  57630. b.push(v.clone());
  57631. }
  57632. }
  57633. var poly;
  57634. if (f.length >= 3) {
  57635. poly = new Polygon(f, polygon.shared);
  57636. if (poly.plane)
  57637. front.push(poly);
  57638. }
  57639. if (b.length >= 3) {
  57640. poly = new Polygon(b, polygon.shared);
  57641. if (poly.plane)
  57642. back.push(poly);
  57643. }
  57644. break;
  57645. }
  57646. };
  57647. return Plane;
  57648. }());
  57649. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  57650. // point is on the plane.
  57651. Plane.EPSILON = 1e-5;
  57652. // # class Polygon
  57653. // Represents a convex polygon. The vertices used to initialize a polygon must
  57654. // be coplanar and form a convex loop.
  57655. //
  57656. // Each convex polygon has a `shared` property, which is shared between all
  57657. // polygons that are clones of each other or were split from the same polygon.
  57658. // This can be used to define per-polygon properties (such as surface color).
  57659. var Polygon = (function () {
  57660. function Polygon(vertices, shared) {
  57661. this.vertices = vertices;
  57662. this.shared = shared;
  57663. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  57664. }
  57665. Polygon.prototype.clone = function () {
  57666. var vertices = this.vertices.map(function (v) { return v.clone(); });
  57667. return new Polygon(vertices, this.shared);
  57668. };
  57669. Polygon.prototype.flip = function () {
  57670. this.vertices.reverse().map(function (v) { v.flip(); });
  57671. this.plane.flip();
  57672. };
  57673. return Polygon;
  57674. }());
  57675. // # class Node
  57676. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  57677. // by picking a polygon to split along. That polygon (and all other coplanar
  57678. // polygons) are added directly to that node and the other polygons are added to
  57679. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  57680. // no distinction between internal and leaf nodes.
  57681. var Node = (function () {
  57682. function Node(polygons) {
  57683. this.plane = null;
  57684. this.front = null;
  57685. this.back = null;
  57686. this.polygons = [];
  57687. if (polygons) {
  57688. this.build(polygons);
  57689. }
  57690. }
  57691. Node.prototype.clone = function () {
  57692. var node = new Node();
  57693. node.plane = this.plane && this.plane.clone();
  57694. node.front = this.front && this.front.clone();
  57695. node.back = this.back && this.back.clone();
  57696. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  57697. return node;
  57698. };
  57699. // Convert solid space to empty space and empty space to solid space.
  57700. Node.prototype.invert = function () {
  57701. for (var i = 0; i < this.polygons.length; i++) {
  57702. this.polygons[i].flip();
  57703. }
  57704. if (this.plane) {
  57705. this.plane.flip();
  57706. }
  57707. if (this.front) {
  57708. this.front.invert();
  57709. }
  57710. if (this.back) {
  57711. this.back.invert();
  57712. }
  57713. var temp = this.front;
  57714. this.front = this.back;
  57715. this.back = temp;
  57716. };
  57717. // Recursively remove all polygons in `polygons` that are inside this BSP
  57718. // tree.
  57719. Node.prototype.clipPolygons = function (polygons) {
  57720. if (!this.plane)
  57721. return polygons.slice();
  57722. var front = [], back = [];
  57723. for (var i = 0; i < polygons.length; i++) {
  57724. this.plane.splitPolygon(polygons[i], front, back, front, back);
  57725. }
  57726. if (this.front) {
  57727. front = this.front.clipPolygons(front);
  57728. }
  57729. if (this.back) {
  57730. back = this.back.clipPolygons(back);
  57731. }
  57732. else {
  57733. back = [];
  57734. }
  57735. return front.concat(back);
  57736. };
  57737. // Remove all polygons in this BSP tree that are inside the other BSP tree
  57738. // `bsp`.
  57739. Node.prototype.clipTo = function (bsp) {
  57740. this.polygons = bsp.clipPolygons(this.polygons);
  57741. if (this.front)
  57742. this.front.clipTo(bsp);
  57743. if (this.back)
  57744. this.back.clipTo(bsp);
  57745. };
  57746. // Return a list of all polygons in this BSP tree.
  57747. Node.prototype.allPolygons = function () {
  57748. var polygons = this.polygons.slice();
  57749. if (this.front)
  57750. polygons = polygons.concat(this.front.allPolygons());
  57751. if (this.back)
  57752. polygons = polygons.concat(this.back.allPolygons());
  57753. return polygons;
  57754. };
  57755. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  57756. // new polygons are filtered down to the bottom of the tree and become new
  57757. // nodes there. Each set of polygons is partitioned using the first polygon
  57758. // (no heuristic is used to pick a good split).
  57759. Node.prototype.build = function (polygons) {
  57760. if (!polygons.length)
  57761. return;
  57762. if (!this.plane)
  57763. this.plane = polygons[0].plane.clone();
  57764. var front = [], back = [];
  57765. for (var i = 0; i < polygons.length; i++) {
  57766. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  57767. }
  57768. if (front.length) {
  57769. if (!this.front)
  57770. this.front = new Node();
  57771. this.front.build(front);
  57772. }
  57773. if (back.length) {
  57774. if (!this.back)
  57775. this.back = new Node();
  57776. this.back.build(back);
  57777. }
  57778. };
  57779. return Node;
  57780. }());
  57781. var CSG = (function () {
  57782. function CSG() {
  57783. this.polygons = new Array();
  57784. }
  57785. // Convert BABYLON.Mesh to BABYLON.CSG
  57786. CSG.FromMesh = function (mesh) {
  57787. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  57788. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  57789. if (mesh instanceof BABYLON.Mesh) {
  57790. mesh.computeWorldMatrix(true);
  57791. matrix = mesh.getWorldMatrix();
  57792. meshPosition = mesh.position.clone();
  57793. meshRotation = mesh.rotation.clone();
  57794. if (mesh.rotationQuaternion) {
  57795. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  57796. }
  57797. meshScaling = mesh.scaling.clone();
  57798. }
  57799. else {
  57800. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  57801. }
  57802. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57803. var subMeshes = mesh.subMeshes;
  57804. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  57805. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  57806. vertices = [];
  57807. for (var j = 0; j < 3; j++) {
  57808. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  57809. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  57810. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  57811. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  57812. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  57813. vertex = new Vertex(position, normal, uv);
  57814. vertices.push(vertex);
  57815. }
  57816. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  57817. // To handle the case of degenerated triangle
  57818. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  57819. if (polygon.plane)
  57820. polygons.push(polygon);
  57821. }
  57822. }
  57823. var csg = CSG.FromPolygons(polygons);
  57824. csg.matrix = matrix;
  57825. csg.position = meshPosition;
  57826. csg.rotation = meshRotation;
  57827. csg.scaling = meshScaling;
  57828. csg.rotationQuaternion = meshRotationQuaternion;
  57829. currentCSGMeshId++;
  57830. return csg;
  57831. };
  57832. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  57833. CSG.FromPolygons = function (polygons) {
  57834. var csg = new CSG();
  57835. csg.polygons = polygons;
  57836. return csg;
  57837. };
  57838. CSG.prototype.clone = function () {
  57839. var csg = new CSG();
  57840. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  57841. csg.copyTransformAttributes(this);
  57842. return csg;
  57843. };
  57844. CSG.prototype.toPolygons = function () {
  57845. return this.polygons;
  57846. };
  57847. CSG.prototype.union = function (csg) {
  57848. var a = new Node(this.clone().polygons);
  57849. var b = new Node(csg.clone().polygons);
  57850. a.clipTo(b);
  57851. b.clipTo(a);
  57852. b.invert();
  57853. b.clipTo(a);
  57854. b.invert();
  57855. a.build(b.allPolygons());
  57856. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  57857. };
  57858. CSG.prototype.unionInPlace = function (csg) {
  57859. var a = new Node(this.polygons);
  57860. var b = new Node(csg.polygons);
  57861. a.clipTo(b);
  57862. b.clipTo(a);
  57863. b.invert();
  57864. b.clipTo(a);
  57865. b.invert();
  57866. a.build(b.allPolygons());
  57867. this.polygons = a.allPolygons();
  57868. };
  57869. CSG.prototype.subtract = function (csg) {
  57870. var a = new Node(this.clone().polygons);
  57871. var b = new Node(csg.clone().polygons);
  57872. a.invert();
  57873. a.clipTo(b);
  57874. b.clipTo(a);
  57875. b.invert();
  57876. b.clipTo(a);
  57877. b.invert();
  57878. a.build(b.allPolygons());
  57879. a.invert();
  57880. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  57881. };
  57882. CSG.prototype.subtractInPlace = function (csg) {
  57883. var a = new Node(this.polygons);
  57884. var b = new Node(csg.polygons);
  57885. a.invert();
  57886. a.clipTo(b);
  57887. b.clipTo(a);
  57888. b.invert();
  57889. b.clipTo(a);
  57890. b.invert();
  57891. a.build(b.allPolygons());
  57892. a.invert();
  57893. this.polygons = a.allPolygons();
  57894. };
  57895. CSG.prototype.intersect = function (csg) {
  57896. var a = new Node(this.clone().polygons);
  57897. var b = new Node(csg.clone().polygons);
  57898. a.invert();
  57899. b.clipTo(a);
  57900. b.invert();
  57901. a.clipTo(b);
  57902. b.clipTo(a);
  57903. a.build(b.allPolygons());
  57904. a.invert();
  57905. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  57906. };
  57907. CSG.prototype.intersectInPlace = function (csg) {
  57908. var a = new Node(this.polygons);
  57909. var b = new Node(csg.polygons);
  57910. a.invert();
  57911. b.clipTo(a);
  57912. b.invert();
  57913. a.clipTo(b);
  57914. b.clipTo(a);
  57915. a.build(b.allPolygons());
  57916. a.invert();
  57917. this.polygons = a.allPolygons();
  57918. };
  57919. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  57920. // not modified.
  57921. CSG.prototype.inverse = function () {
  57922. var csg = this.clone();
  57923. csg.inverseInPlace();
  57924. return csg;
  57925. };
  57926. CSG.prototype.inverseInPlace = function () {
  57927. this.polygons.map(function (p) { p.flip(); });
  57928. };
  57929. // This is used to keep meshes transformations so they can be restored
  57930. // when we build back a Babylon Mesh
  57931. // NB : All CSG operations are performed in world coordinates
  57932. CSG.prototype.copyTransformAttributes = function (csg) {
  57933. this.matrix = csg.matrix;
  57934. this.position = csg.position;
  57935. this.rotation = csg.rotation;
  57936. this.scaling = csg.scaling;
  57937. this.rotationQuaternion = csg.rotationQuaternion;
  57938. return this;
  57939. };
  57940. // Build Raw mesh from CSG
  57941. // Coordinates here are in world space
  57942. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  57943. var matrix = this.matrix.clone();
  57944. matrix.invert();
  57945. 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;
  57946. if (keepSubMeshes) {
  57947. // Sort Polygons, since subMeshes are indices range
  57948. polygons.sort(function (a, b) {
  57949. if (a.shared.meshId === b.shared.meshId) {
  57950. return a.shared.subMeshId - b.shared.subMeshId;
  57951. }
  57952. else {
  57953. return a.shared.meshId - b.shared.meshId;
  57954. }
  57955. });
  57956. }
  57957. for (var i = 0, il = polygons.length; i < il; i++) {
  57958. polygon = polygons[i];
  57959. // Building SubMeshes
  57960. if (!subMesh_dict[polygon.shared.meshId]) {
  57961. subMesh_dict[polygon.shared.meshId] = {};
  57962. }
  57963. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  57964. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  57965. indexStart: +Infinity,
  57966. indexEnd: -Infinity,
  57967. materialIndex: polygon.shared.materialIndex
  57968. };
  57969. }
  57970. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  57971. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  57972. polygonIndices[0] = 0;
  57973. polygonIndices[1] = j - 1;
  57974. polygonIndices[2] = j;
  57975. for (var k = 0; k < 3; k++) {
  57976. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  57977. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  57978. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  57979. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  57980. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  57981. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  57982. // Check if 2 points can be merged
  57983. if (!(typeof vertex_idx !== 'undefined' &&
  57984. normals[vertex_idx * 3] === localNormal.x &&
  57985. normals[vertex_idx * 3 + 1] === localNormal.y &&
  57986. normals[vertex_idx * 3 + 2] === localNormal.z &&
  57987. uvs[vertex_idx * 2] === uv.x &&
  57988. uvs[vertex_idx * 2 + 1] === uv.y)) {
  57989. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  57990. uvs.push(uv.x, uv.y);
  57991. normals.push(normal.x, normal.y, normal.z);
  57992. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  57993. }
  57994. indices.push(vertex_idx);
  57995. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  57996. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  57997. currentIndex++;
  57998. }
  57999. }
  58000. }
  58001. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  58002. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  58003. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  58004. mesh.setIndices(indices);
  58005. if (keepSubMeshes) {
  58006. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  58007. var materialIndexOffset = 0, materialMaxIndex;
  58008. mesh.subMeshes = new Array();
  58009. for (var m in subMesh_dict) {
  58010. materialMaxIndex = -1;
  58011. for (var sm in subMesh_dict[m]) {
  58012. subMesh_obj = subMesh_dict[m][sm];
  58013. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  58014. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  58015. }
  58016. materialIndexOffset += ++materialMaxIndex;
  58017. }
  58018. }
  58019. return mesh;
  58020. };
  58021. // Build Mesh from CSG taking material and transforms into account
  58022. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  58023. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  58024. mesh.material = material;
  58025. mesh.position.copyFrom(this.position);
  58026. mesh.rotation.copyFrom(this.rotation);
  58027. if (this.rotationQuaternion) {
  58028. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  58029. }
  58030. mesh.scaling.copyFrom(this.scaling);
  58031. mesh.computeWorldMatrix(true);
  58032. return mesh;
  58033. };
  58034. return CSG;
  58035. }());
  58036. BABYLON.CSG = CSG;
  58037. })(BABYLON || (BABYLON = {}));
  58038. //# sourceMappingURL=babylon.csg.js.map
  58039. var BABYLON;
  58040. (function (BABYLON) {
  58041. var LensFlare = (function () {
  58042. function LensFlare(size, position, color, imgUrl, system) {
  58043. this.size = size;
  58044. this.position = position;
  58045. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  58046. this.dispose = function () {
  58047. if (this.texture) {
  58048. this.texture.dispose();
  58049. }
  58050. // Remove from scene
  58051. var index = this._system.lensFlares.indexOf(this);
  58052. this._system.lensFlares.splice(index, 1);
  58053. };
  58054. this.color = color || new BABYLON.Color3(1, 1, 1);
  58055. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  58056. this._system = system;
  58057. system.lensFlares.push(this);
  58058. }
  58059. return LensFlare;
  58060. }());
  58061. BABYLON.LensFlare = LensFlare;
  58062. })(BABYLON || (BABYLON = {}));
  58063. //# sourceMappingURL=babylon.lensFlare.js.map
  58064. var BABYLON;
  58065. (function (BABYLON) {
  58066. var LensFlareSystem = (function () {
  58067. function LensFlareSystem(name, emitter, scene) {
  58068. this.name = name;
  58069. this.lensFlares = new Array();
  58070. this.borderLimit = 300;
  58071. this.viewportBorder = 0;
  58072. this.layerMask = 0x0FFFFFFF;
  58073. this._vertexBuffers = {};
  58074. this._isEnabled = true;
  58075. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58076. this._emitter = emitter;
  58077. this.id = name;
  58078. scene.lensFlareSystems.push(this);
  58079. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  58080. var engine = scene.getEngine();
  58081. // VBO
  58082. var vertices = [];
  58083. vertices.push(1, 1);
  58084. vertices.push(-1, 1);
  58085. vertices.push(-1, -1);
  58086. vertices.push(1, -1);
  58087. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  58088. // Indices
  58089. var indices = [];
  58090. indices.push(0);
  58091. indices.push(1);
  58092. indices.push(2);
  58093. indices.push(0);
  58094. indices.push(2);
  58095. indices.push(3);
  58096. this._indexBuffer = engine.createIndexBuffer(indices);
  58097. // Effects
  58098. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  58099. }
  58100. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  58101. get: function () {
  58102. return this._isEnabled;
  58103. },
  58104. set: function (value) {
  58105. this._isEnabled = value;
  58106. },
  58107. enumerable: true,
  58108. configurable: true
  58109. });
  58110. LensFlareSystem.prototype.getScene = function () {
  58111. return this._scene;
  58112. };
  58113. LensFlareSystem.prototype.getEmitter = function () {
  58114. return this._emitter;
  58115. };
  58116. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  58117. this._emitter = newEmitter;
  58118. };
  58119. LensFlareSystem.prototype.getEmitterPosition = function () {
  58120. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  58121. };
  58122. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  58123. var position = this.getEmitterPosition();
  58124. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  58125. this._positionX = position.x;
  58126. this._positionY = position.y;
  58127. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  58128. if (this.viewportBorder > 0) {
  58129. globalViewport.x -= this.viewportBorder;
  58130. globalViewport.y -= this.viewportBorder;
  58131. globalViewport.width += this.viewportBorder * 2;
  58132. globalViewport.height += this.viewportBorder * 2;
  58133. position.x += this.viewportBorder;
  58134. position.y += this.viewportBorder;
  58135. this._positionX += this.viewportBorder;
  58136. this._positionY += this.viewportBorder;
  58137. }
  58138. if (position.z > 0) {
  58139. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  58140. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  58141. return true;
  58142. }
  58143. return true;
  58144. }
  58145. return false;
  58146. };
  58147. LensFlareSystem.prototype._isVisible = function () {
  58148. if (!this._isEnabled) {
  58149. return false;
  58150. }
  58151. var emitterPosition = this.getEmitterPosition();
  58152. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  58153. var distance = direction.length();
  58154. direction.normalize();
  58155. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  58156. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  58157. return !pickInfo.hit || pickInfo.distance > distance;
  58158. };
  58159. LensFlareSystem.prototype.render = function () {
  58160. if (!this._effect.isReady())
  58161. return false;
  58162. var engine = this._scene.getEngine();
  58163. var viewport = this._scene.activeCamera.viewport;
  58164. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  58165. // Position
  58166. if (!this.computeEffectivePosition(globalViewport)) {
  58167. return false;
  58168. }
  58169. // Visibility
  58170. if (!this._isVisible()) {
  58171. return false;
  58172. }
  58173. // Intensity
  58174. var awayX;
  58175. var awayY;
  58176. if (this._positionX < this.borderLimit + globalViewport.x) {
  58177. awayX = this.borderLimit + globalViewport.x - this._positionX;
  58178. }
  58179. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  58180. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  58181. }
  58182. else {
  58183. awayX = 0;
  58184. }
  58185. if (this._positionY < this.borderLimit + globalViewport.y) {
  58186. awayY = this.borderLimit + globalViewport.y - this._positionY;
  58187. }
  58188. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  58189. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  58190. }
  58191. else {
  58192. awayY = 0;
  58193. }
  58194. var away = (awayX > awayY) ? awayX : awayY;
  58195. away -= this.viewportBorder;
  58196. if (away > this.borderLimit) {
  58197. away = this.borderLimit;
  58198. }
  58199. var intensity = 1.0 - (away / this.borderLimit);
  58200. if (intensity < 0) {
  58201. return false;
  58202. }
  58203. if (intensity > 1.0) {
  58204. intensity = 1.0;
  58205. }
  58206. if (this.viewportBorder > 0) {
  58207. globalViewport.x += this.viewportBorder;
  58208. globalViewport.y += this.viewportBorder;
  58209. globalViewport.width -= this.viewportBorder * 2;
  58210. globalViewport.height -= this.viewportBorder * 2;
  58211. this._positionX -= this.viewportBorder;
  58212. this._positionY -= this.viewportBorder;
  58213. }
  58214. // Position
  58215. var centerX = globalViewport.x + globalViewport.width / 2;
  58216. var centerY = globalViewport.y + globalViewport.height / 2;
  58217. var distX = centerX - this._positionX;
  58218. var distY = centerY - this._positionY;
  58219. // Effects
  58220. engine.enableEffect(this._effect);
  58221. engine.setState(false);
  58222. engine.setDepthBuffer(false);
  58223. // VBOs
  58224. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  58225. // Flares
  58226. for (var index = 0; index < this.lensFlares.length; index++) {
  58227. var flare = this.lensFlares[index];
  58228. engine.setAlphaMode(flare.alphaMode);
  58229. var x = centerX - (distX * flare.position);
  58230. var y = centerY - (distY * flare.position);
  58231. var cw = flare.size;
  58232. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  58233. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  58234. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  58235. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  58236. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  58237. // Texture
  58238. this._effect.setTexture("textureSampler", flare.texture);
  58239. // Color
  58240. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  58241. // Draw order
  58242. engine.draw(true, 0, 6);
  58243. }
  58244. engine.setDepthBuffer(true);
  58245. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58246. return true;
  58247. };
  58248. LensFlareSystem.prototype.dispose = function () {
  58249. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58250. if (vertexBuffer) {
  58251. vertexBuffer.dispose();
  58252. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  58253. }
  58254. if (this._indexBuffer) {
  58255. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58256. this._indexBuffer = null;
  58257. }
  58258. while (this.lensFlares.length) {
  58259. this.lensFlares[0].dispose();
  58260. }
  58261. // Remove from scene
  58262. var index = this._scene.lensFlareSystems.indexOf(this);
  58263. this._scene.lensFlareSystems.splice(index, 1);
  58264. };
  58265. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  58266. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  58267. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  58268. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  58269. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  58270. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  58271. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  58272. var parsedFlare = parsedLensFlareSystem.flares[index];
  58273. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  58274. }
  58275. return lensFlareSystem;
  58276. };
  58277. LensFlareSystem.prototype.serialize = function () {
  58278. var serializationObject = {};
  58279. serializationObject.id = this.id;
  58280. serializationObject.name = this.name;
  58281. serializationObject.emitterId = this.getEmitter().id;
  58282. serializationObject.borderLimit = this.borderLimit;
  58283. serializationObject.flares = [];
  58284. for (var index = 0; index < this.lensFlares.length; index++) {
  58285. var flare = this.lensFlares[index];
  58286. serializationObject.flares.push({
  58287. size: flare.size,
  58288. position: flare.position,
  58289. color: flare.color.asArray(),
  58290. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  58291. });
  58292. }
  58293. return serializationObject;
  58294. };
  58295. return LensFlareSystem;
  58296. }());
  58297. BABYLON.LensFlareSystem = LensFlareSystem;
  58298. })(BABYLON || (BABYLON = {}));
  58299. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  58300. var BABYLON;
  58301. (function (BABYLON) {
  58302. /**
  58303. * This is a holder class for the physics joint created by the physics plugin.
  58304. * It holds a set of functions to control the underlying joint.
  58305. */
  58306. var PhysicsJoint = (function () {
  58307. function PhysicsJoint(type, jointData) {
  58308. this.type = type;
  58309. this.jointData = jointData;
  58310. jointData.nativeParams = jointData.nativeParams || {};
  58311. }
  58312. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  58313. get: function () {
  58314. return this._physicsJoint;
  58315. },
  58316. set: function (newJoint) {
  58317. if (this._physicsJoint) {
  58318. //remove from the wolrd
  58319. }
  58320. this._physicsJoint = newJoint;
  58321. },
  58322. enumerable: true,
  58323. configurable: true
  58324. });
  58325. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  58326. set: function (physicsPlugin) {
  58327. this._physicsPlugin = physicsPlugin;
  58328. },
  58329. enumerable: true,
  58330. configurable: true
  58331. });
  58332. /**
  58333. * Execute a function that is physics-plugin specific.
  58334. * @param {Function} func the function that will be executed.
  58335. * It accepts two parameters: the physics world and the physics joint.
  58336. */
  58337. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  58338. func(this._physicsPlugin.world, this._physicsJoint);
  58339. };
  58340. return PhysicsJoint;
  58341. }());
  58342. //TODO check if the native joints are the same
  58343. //Joint Types
  58344. PhysicsJoint.DistanceJoint = 0;
  58345. PhysicsJoint.HingeJoint = 1;
  58346. PhysicsJoint.BallAndSocketJoint = 2;
  58347. PhysicsJoint.WheelJoint = 3;
  58348. PhysicsJoint.SliderJoint = 4;
  58349. //OIMO
  58350. PhysicsJoint.PrismaticJoint = 5;
  58351. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  58352. PhysicsJoint.UniversalJoint = 6;
  58353. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  58354. //Cannon
  58355. //Similar to a Ball-Joint. Different in params
  58356. PhysicsJoint.PointToPointJoint = 8;
  58357. //Cannon only at the moment
  58358. PhysicsJoint.SpringJoint = 9;
  58359. PhysicsJoint.LockJoint = 10;
  58360. BABYLON.PhysicsJoint = PhysicsJoint;
  58361. /**
  58362. * A class representing a physics distance joint.
  58363. */
  58364. var DistanceJoint = (function (_super) {
  58365. __extends(DistanceJoint, _super);
  58366. function DistanceJoint(jointData) {
  58367. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  58368. }
  58369. /**
  58370. * Update the predefined distance.
  58371. */
  58372. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  58373. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  58374. };
  58375. return DistanceJoint;
  58376. }(PhysicsJoint));
  58377. BABYLON.DistanceJoint = DistanceJoint;
  58378. var MotorEnabledJoint = (function (_super) {
  58379. __extends(MotorEnabledJoint, _super);
  58380. function MotorEnabledJoint(type, jointData) {
  58381. return _super.call(this, type, jointData) || this;
  58382. }
  58383. /**
  58384. * Set the motor values.
  58385. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58386. * @param {number} force the force to apply
  58387. * @param {number} maxForce max force for this motor.
  58388. */
  58389. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  58390. this._physicsPlugin.setMotor(this, force, maxForce);
  58391. };
  58392. /**
  58393. * Set the motor's limits.
  58394. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58395. */
  58396. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  58397. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  58398. };
  58399. return MotorEnabledJoint;
  58400. }(PhysicsJoint));
  58401. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  58402. /**
  58403. * This class represents a single hinge physics joint
  58404. */
  58405. var HingeJoint = (function (_super) {
  58406. __extends(HingeJoint, _super);
  58407. function HingeJoint(jointData) {
  58408. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  58409. }
  58410. /**
  58411. * Set the motor values.
  58412. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58413. * @param {number} force the force to apply
  58414. * @param {number} maxForce max force for this motor.
  58415. */
  58416. HingeJoint.prototype.setMotor = function (force, maxForce) {
  58417. this._physicsPlugin.setMotor(this, force, maxForce);
  58418. };
  58419. /**
  58420. * Set the motor's limits.
  58421. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58422. */
  58423. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  58424. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  58425. };
  58426. return HingeJoint;
  58427. }(MotorEnabledJoint));
  58428. BABYLON.HingeJoint = HingeJoint;
  58429. /**
  58430. * This class represents a dual hinge physics joint (same as wheel joint)
  58431. */
  58432. var Hinge2Joint = (function (_super) {
  58433. __extends(Hinge2Joint, _super);
  58434. function Hinge2Joint(jointData) {
  58435. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  58436. }
  58437. /**
  58438. * Set the motor values.
  58439. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58440. * @param {number} force the force to apply
  58441. * @param {number} maxForce max force for this motor.
  58442. * @param {motorIndex} the motor's index, 0 or 1.
  58443. */
  58444. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  58445. if (motorIndex === void 0) { motorIndex = 0; }
  58446. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  58447. };
  58448. /**
  58449. * Set the motor limits.
  58450. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58451. * @param {number} upperLimit the upper limit
  58452. * @param {number} lowerLimit lower limit
  58453. * @param {motorIndex} the motor's index, 0 or 1.
  58454. */
  58455. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  58456. if (motorIndex === void 0) { motorIndex = 0; }
  58457. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  58458. };
  58459. return Hinge2Joint;
  58460. }(MotorEnabledJoint));
  58461. BABYLON.Hinge2Joint = Hinge2Joint;
  58462. })(BABYLON || (BABYLON = {}));
  58463. //# sourceMappingURL=babylon.physicsJoint.js.map
  58464. var BABYLON;
  58465. (function (BABYLON) {
  58466. var PhysicsImpostor = (function () {
  58467. function PhysicsImpostor(object, type, _options, _scene) {
  58468. if (_options === void 0) { _options = { mass: 0 }; }
  58469. var _this = this;
  58470. this.object = object;
  58471. this.type = type;
  58472. this._options = _options;
  58473. this._scene = _scene;
  58474. this._bodyUpdateRequired = false;
  58475. this._onBeforePhysicsStepCallbacks = new Array();
  58476. this._onAfterPhysicsStepCallbacks = new Array();
  58477. this._onPhysicsCollideCallbacks = [];
  58478. this._deltaPosition = BABYLON.Vector3.Zero();
  58479. this._isDisposed = false;
  58480. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  58481. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  58482. /**
  58483. * this function is executed by the physics engine.
  58484. */
  58485. this.beforeStep = function () {
  58486. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  58487. //conjugate deltaRotation
  58488. if (_this._deltaRotationConjugated) {
  58489. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  58490. }
  58491. else {
  58492. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  58493. }
  58494. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  58495. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  58496. func(_this);
  58497. });
  58498. };
  58499. /**
  58500. * this function is executed by the physics engine.
  58501. */
  58502. this.afterStep = function () {
  58503. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  58504. func(_this);
  58505. });
  58506. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  58507. _this.object.position.addInPlace(_this._deltaPosition);
  58508. if (_this._deltaRotation) {
  58509. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  58510. }
  58511. };
  58512. /**
  58513. * Legacy collision detection event support
  58514. */
  58515. this.onCollideEvent = null;
  58516. //event and body object due to cannon's event-based architecture.
  58517. this.onCollide = function (e) {
  58518. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  58519. return;
  58520. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  58521. if (otherImpostor) {
  58522. // Legacy collision detection event support
  58523. if (_this.onCollideEvent) {
  58524. _this.onCollideEvent(_this, otherImpostor);
  58525. }
  58526. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  58527. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  58528. }).forEach(function (obj) {
  58529. obj.callback(_this, otherImpostor);
  58530. });
  58531. }
  58532. };
  58533. //sanity check!
  58534. if (!this.object) {
  58535. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  58536. return;
  58537. }
  58538. //legacy support for old syntax.
  58539. if (!this._scene && object.getScene) {
  58540. this._scene = object.getScene();
  58541. }
  58542. this._physicsEngine = this._scene.getPhysicsEngine();
  58543. if (!this._physicsEngine) {
  58544. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  58545. }
  58546. else {
  58547. //set the object's quaternion, if not set
  58548. if (!this.object.rotationQuaternion) {
  58549. if (this.object.rotation) {
  58550. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  58551. }
  58552. else {
  58553. this.object.rotationQuaternion = new BABYLON.Quaternion();
  58554. }
  58555. }
  58556. //default options params
  58557. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  58558. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  58559. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  58560. this._joints = [];
  58561. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  58562. if (!this.object.parent) {
  58563. this._init();
  58564. }
  58565. else if (this.object.parent.physicsImpostor) {
  58566. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  58567. }
  58568. }
  58569. }
  58570. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  58571. get: function () {
  58572. return this._isDisposed;
  58573. },
  58574. enumerable: true,
  58575. configurable: true
  58576. });
  58577. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  58578. get: function () {
  58579. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  58580. },
  58581. set: function (value) {
  58582. this.setMass(value);
  58583. },
  58584. enumerable: true,
  58585. configurable: true
  58586. });
  58587. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  58588. get: function () {
  58589. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  58590. },
  58591. set: function (value) {
  58592. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  58593. },
  58594. enumerable: true,
  58595. configurable: true
  58596. });
  58597. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  58598. get: function () {
  58599. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  58600. },
  58601. set: function (value) {
  58602. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  58603. },
  58604. enumerable: true,
  58605. configurable: true
  58606. });
  58607. /**
  58608. * This function will completly initialize this impostor.
  58609. * It will create a new body - but only if this mesh has no parent.
  58610. * If it has, this impostor will not be used other than to define the impostor
  58611. * of the child mesh.
  58612. */
  58613. PhysicsImpostor.prototype._init = function () {
  58614. this._physicsEngine.removeImpostor(this);
  58615. this.physicsBody = null;
  58616. this._parent = this._parent || this._getPhysicsParent();
  58617. if (!this.parent) {
  58618. this._physicsEngine.addImpostor(this);
  58619. }
  58620. };
  58621. PhysicsImpostor.prototype._getPhysicsParent = function () {
  58622. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  58623. var parentMesh = this.object.parent;
  58624. return parentMesh.physicsImpostor;
  58625. }
  58626. return;
  58627. };
  58628. /**
  58629. * Should a new body be generated.
  58630. */
  58631. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  58632. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  58633. };
  58634. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  58635. this.forceUpdate();
  58636. };
  58637. /**
  58638. * Force a regeneration of this or the parent's impostor's body.
  58639. * Use under cautious - This will remove all joints already implemented.
  58640. */
  58641. PhysicsImpostor.prototype.forceUpdate = function () {
  58642. this._init();
  58643. if (this.parent) {
  58644. this.parent.forceUpdate();
  58645. }
  58646. };
  58647. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  58648. /*public get mesh(): AbstractMesh {
  58649. return this._mesh;
  58650. }*/
  58651. /**
  58652. * Gets the body that holds this impostor. Either its own, or its parent.
  58653. */
  58654. get: function () {
  58655. return this._parent ? this._parent.physicsBody : this._physicsBody;
  58656. },
  58657. /**
  58658. * Set the physics body. Used mainly by the physics engine/plugin
  58659. */
  58660. set: function (physicsBody) {
  58661. if (this._physicsBody) {
  58662. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  58663. }
  58664. this._physicsBody = physicsBody;
  58665. this.resetUpdateFlags();
  58666. },
  58667. enumerable: true,
  58668. configurable: true
  58669. });
  58670. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  58671. get: function () {
  58672. return this._parent;
  58673. },
  58674. set: function (value) {
  58675. this._parent = value;
  58676. },
  58677. enumerable: true,
  58678. configurable: true
  58679. });
  58680. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  58681. this._bodyUpdateRequired = false;
  58682. };
  58683. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  58684. if (this.object.getBoundingInfo) {
  58685. var q = this.object.rotationQuaternion;
  58686. //reset rotation
  58687. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  58688. //calculate the world matrix with no rotation
  58689. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  58690. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  58691. //bring back the rotation
  58692. this.object.rotationQuaternion = q;
  58693. //calculate the world matrix with the new rotation
  58694. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  58695. return size;
  58696. }
  58697. else {
  58698. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  58699. }
  58700. };
  58701. PhysicsImpostor.prototype.getObjectCenter = function () {
  58702. if (this.object.getBoundingInfo) {
  58703. return this.object.getBoundingInfo().boundingBox.centerWorld;
  58704. }
  58705. else {
  58706. return this.object.position;
  58707. }
  58708. };
  58709. /**
  58710. * Get a specific parametes from the options parameter.
  58711. */
  58712. PhysicsImpostor.prototype.getParam = function (paramName) {
  58713. return this._options[paramName];
  58714. };
  58715. /**
  58716. * Sets a specific parameter in the options given to the physics plugin
  58717. */
  58718. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  58719. this._options[paramName] = value;
  58720. this._bodyUpdateRequired = true;
  58721. };
  58722. /**
  58723. * Specifically change the body's mass option. Won't recreate the physics body object
  58724. */
  58725. PhysicsImpostor.prototype.setMass = function (mass) {
  58726. if (this.getParam("mass") !== mass) {
  58727. this.setParam("mass", mass);
  58728. }
  58729. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  58730. };
  58731. PhysicsImpostor.prototype.getLinearVelocity = function () {
  58732. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  58733. };
  58734. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  58735. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  58736. };
  58737. PhysicsImpostor.prototype.getAngularVelocity = function () {
  58738. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  58739. };
  58740. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  58741. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  58742. };
  58743. /**
  58744. * Execute a function with the physics plugin native code.
  58745. * Provide a function the will have two variables - the world object and the physics body object.
  58746. */
  58747. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  58748. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  58749. };
  58750. /**
  58751. * Register a function that will be executed before the physics world is stepping forward.
  58752. */
  58753. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  58754. this._onBeforePhysicsStepCallbacks.push(func);
  58755. };
  58756. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  58757. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  58758. if (index > -1) {
  58759. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  58760. }
  58761. else {
  58762. BABYLON.Tools.Warn("Function to remove was not found");
  58763. }
  58764. };
  58765. /**
  58766. * Register a function that will be executed after the physics step
  58767. */
  58768. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  58769. this._onAfterPhysicsStepCallbacks.push(func);
  58770. };
  58771. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  58772. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  58773. if (index > -1) {
  58774. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  58775. }
  58776. else {
  58777. BABYLON.Tools.Warn("Function to remove was not found");
  58778. }
  58779. };
  58780. /**
  58781. * register a function that will be executed when this impostor collides against a different body.
  58782. */
  58783. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  58784. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  58785. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  58786. };
  58787. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  58788. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  58789. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  58790. if (index > -1) {
  58791. this._onPhysicsCollideCallbacks.splice(index, 1);
  58792. }
  58793. else {
  58794. BABYLON.Tools.Warn("Function to remove was not found");
  58795. }
  58796. };
  58797. /**
  58798. * Apply a force
  58799. */
  58800. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  58801. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  58802. };
  58803. /**
  58804. * Apply an impulse
  58805. */
  58806. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  58807. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  58808. };
  58809. /**
  58810. * A help function to create a joint.
  58811. */
  58812. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  58813. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  58814. this.addJoint(otherImpostor, joint);
  58815. };
  58816. /**
  58817. * Add a joint to this impostor with a different impostor.
  58818. */
  58819. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  58820. this._joints.push({
  58821. otherImpostor: otherImpostor,
  58822. joint: joint
  58823. });
  58824. this._physicsEngine.addJoint(this, otherImpostor, joint);
  58825. };
  58826. /**
  58827. * Will keep this body still, in a sleep mode.
  58828. */
  58829. PhysicsImpostor.prototype.sleep = function () {
  58830. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  58831. };
  58832. /**
  58833. * Wake the body up.
  58834. */
  58835. PhysicsImpostor.prototype.wakeUp = function () {
  58836. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  58837. };
  58838. PhysicsImpostor.prototype.clone = function (newObject) {
  58839. if (!newObject)
  58840. return null;
  58841. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  58842. };
  58843. PhysicsImpostor.prototype.dispose = function () {
  58844. var _this = this;
  58845. //no dispose if no physics engine is available.
  58846. if (!this._physicsEngine) {
  58847. return;
  58848. }
  58849. this._joints.forEach(function (j) {
  58850. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  58851. });
  58852. //dispose the physics body
  58853. this._physicsEngine.removeImpostor(this);
  58854. if (this.parent) {
  58855. this.parent.forceUpdate();
  58856. }
  58857. else {
  58858. /*this._object.getChildMeshes().forEach(function(mesh) {
  58859. if (mesh.physicsImpostor) {
  58860. if (disposeChildren) {
  58861. mesh.physicsImpostor.dispose();
  58862. mesh.physicsImpostor = null;
  58863. }
  58864. }
  58865. })*/
  58866. }
  58867. this._isDisposed = true;
  58868. };
  58869. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  58870. this._deltaPosition.copyFrom(position);
  58871. };
  58872. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  58873. if (!this._deltaRotation) {
  58874. this._deltaRotation = new BABYLON.Quaternion();
  58875. }
  58876. this._deltaRotation.copyFrom(rotation);
  58877. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  58878. };
  58879. return PhysicsImpostor;
  58880. }());
  58881. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  58882. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  58883. //Impostor types
  58884. PhysicsImpostor.NoImpostor = 0;
  58885. PhysicsImpostor.SphereImpostor = 1;
  58886. PhysicsImpostor.BoxImpostor = 2;
  58887. PhysicsImpostor.PlaneImpostor = 3;
  58888. PhysicsImpostor.MeshImpostor = 4;
  58889. PhysicsImpostor.CylinderImpostor = 7;
  58890. PhysicsImpostor.ParticleImpostor = 8;
  58891. PhysicsImpostor.HeightmapImpostor = 9;
  58892. BABYLON.PhysicsImpostor = PhysicsImpostor;
  58893. })(BABYLON || (BABYLON = {}));
  58894. //# sourceMappingURL=babylon.physicsImpostor.js.map
  58895. var BABYLON;
  58896. (function (BABYLON) {
  58897. var PhysicsEngine = (function () {
  58898. function PhysicsEngine(gravity, _physicsPlugin) {
  58899. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  58900. this._physicsPlugin = _physicsPlugin;
  58901. //new methods and parameters
  58902. this._impostors = [];
  58903. this._joints = [];
  58904. if (!this._physicsPlugin.isSupported()) {
  58905. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  58906. + "Please make sure it is included.");
  58907. }
  58908. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  58909. this.setGravity(gravity);
  58910. this.setTimeStep();
  58911. }
  58912. PhysicsEngine.prototype.setGravity = function (gravity) {
  58913. this.gravity = gravity;
  58914. this._physicsPlugin.setGravity(this.gravity);
  58915. };
  58916. /**
  58917. * Set the time step of the physics engine.
  58918. * default is 1/60.
  58919. * To slow it down, enter 1/600 for example.
  58920. * To speed it up, 1/30
  58921. * @param {number} newTimeStep the new timestep to apply to this world.
  58922. */
  58923. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  58924. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  58925. this._physicsPlugin.setTimeStep(newTimeStep);
  58926. };
  58927. PhysicsEngine.prototype.dispose = function () {
  58928. this._impostors.forEach(function (impostor) {
  58929. impostor.dispose();
  58930. });
  58931. this._physicsPlugin.dispose();
  58932. };
  58933. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  58934. return this._physicsPlugin.name;
  58935. };
  58936. /**
  58937. * Adding a new impostor for the impostor tracking.
  58938. * This will be done by the impostor itself.
  58939. * @param {PhysicsImpostor} impostor the impostor to add
  58940. */
  58941. PhysicsEngine.prototype.addImpostor = function (impostor) {
  58942. impostor.uniqueId = this._impostors.push(impostor);
  58943. //if no parent, generate the body
  58944. if (!impostor.parent) {
  58945. this._physicsPlugin.generatePhysicsBody(impostor);
  58946. }
  58947. };
  58948. /**
  58949. * Remove an impostor from the engine.
  58950. * This impostor and its mesh will not longer be updated by the physics engine.
  58951. * @param {PhysicsImpostor} impostor the impostor to remove
  58952. */
  58953. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  58954. var index = this._impostors.indexOf(impostor);
  58955. if (index > -1) {
  58956. var removed = this._impostors.splice(index, 1);
  58957. //Is it needed?
  58958. if (removed.length) {
  58959. //this will also remove it from the world.
  58960. removed[0].physicsBody = null;
  58961. }
  58962. }
  58963. };
  58964. /**
  58965. * Add a joint to the physics engine
  58966. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  58967. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  58968. * @param {PhysicsJoint} the joint that will connect both impostors.
  58969. */
  58970. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  58971. var impostorJoint = {
  58972. mainImpostor: mainImpostor,
  58973. connectedImpostor: connectedImpostor,
  58974. joint: joint
  58975. };
  58976. joint.physicsPlugin = this._physicsPlugin;
  58977. this._joints.push(impostorJoint);
  58978. this._physicsPlugin.generateJoint(impostorJoint);
  58979. };
  58980. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  58981. var matchingJoints = this._joints.filter(function (impostorJoint) {
  58982. return (impostorJoint.connectedImpostor === connectedImpostor
  58983. && impostorJoint.joint === joint
  58984. && impostorJoint.mainImpostor === mainImpostor);
  58985. });
  58986. if (matchingJoints.length) {
  58987. this._physicsPlugin.removeJoint(matchingJoints[0]);
  58988. //TODO remove it from the list as well
  58989. }
  58990. };
  58991. /**
  58992. * Called by the scene. no need to call it.
  58993. */
  58994. PhysicsEngine.prototype._step = function (delta) {
  58995. var _this = this;
  58996. //check if any mesh has no body / requires an update
  58997. this._impostors.forEach(function (impostor) {
  58998. if (impostor.isBodyInitRequired()) {
  58999. _this._physicsPlugin.generatePhysicsBody(impostor);
  59000. }
  59001. });
  59002. if (delta > 0.1) {
  59003. delta = 0.1;
  59004. }
  59005. else if (delta <= 0) {
  59006. delta = 1.0 / 60.0;
  59007. }
  59008. this._physicsPlugin.executeStep(delta, this._impostors);
  59009. };
  59010. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  59011. return this._physicsPlugin;
  59012. };
  59013. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  59014. for (var i = 0; i < this._impostors.length; ++i) {
  59015. if (this._impostors[i].object === object) {
  59016. return this._impostors[i];
  59017. }
  59018. }
  59019. };
  59020. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  59021. for (var i = 0; i < this._impostors.length; ++i) {
  59022. if (this._impostors[i].physicsBody === body) {
  59023. return this._impostors[i];
  59024. }
  59025. }
  59026. };
  59027. return PhysicsEngine;
  59028. }());
  59029. // Statics
  59030. PhysicsEngine.Epsilon = 0.001;
  59031. BABYLON.PhysicsEngine = PhysicsEngine;
  59032. })(BABYLON || (BABYLON = {}));
  59033. //# sourceMappingURL=babylon.physicsEngine.js.map
  59034. var BABYLON;
  59035. (function (BABYLON) {
  59036. var CannonJSPlugin = (function () {
  59037. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  59038. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  59039. if (iterations === void 0) { iterations = 10; }
  59040. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  59041. this.name = "CannonJSPlugin";
  59042. this._physicsMaterials = [];
  59043. this._fixedTimeStep = 1 / 60;
  59044. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  59045. this._currentCollisionGroup = 2;
  59046. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  59047. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  59048. this._tmpPosition = BABYLON.Vector3.Zero();
  59049. this._tmpQuaternion = new BABYLON.Quaternion();
  59050. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  59051. this._tmpDeltaRotation = new BABYLON.Quaternion();
  59052. this._tmpUnityRotation = new BABYLON.Quaternion();
  59053. if (!this.isSupported()) {
  59054. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  59055. return;
  59056. }
  59057. this.world = new CANNON.World();
  59058. this.world.broadphase = new CANNON.NaiveBroadphase();
  59059. this.world.solver.iterations = iterations;
  59060. }
  59061. CannonJSPlugin.prototype.setGravity = function (gravity) {
  59062. this.world.gravity.copy(gravity);
  59063. };
  59064. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  59065. this._fixedTimeStep = timeStep;
  59066. };
  59067. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  59068. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  59069. };
  59070. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  59071. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  59072. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  59073. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  59074. };
  59075. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  59076. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  59077. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  59078. impostor.physicsBody.applyForce(impulse, worldPoint);
  59079. };
  59080. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  59081. //parent-child relationship. Does this impostor has a parent impostor?
  59082. if (impostor.parent) {
  59083. if (impostor.physicsBody) {
  59084. this.removePhysicsBody(impostor);
  59085. //TODO is that needed?
  59086. impostor.forceUpdate();
  59087. }
  59088. return;
  59089. }
  59090. //should a new body be created for this impostor?
  59091. if (impostor.isBodyInitRequired()) {
  59092. var shape = this._createShape(impostor);
  59093. //unregister events, if body is being changed
  59094. var oldBody = impostor.physicsBody;
  59095. if (oldBody) {
  59096. this.removePhysicsBody(impostor);
  59097. }
  59098. //create the body and material
  59099. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  59100. var bodyCreationObject = {
  59101. mass: impostor.getParam("mass"),
  59102. material: material
  59103. };
  59104. // A simple extend, in case native options were used.
  59105. var nativeOptions = impostor.getParam("nativeOptions");
  59106. for (var key in nativeOptions) {
  59107. if (nativeOptions.hasOwnProperty(key)) {
  59108. bodyCreationObject[key] = nativeOptions[key];
  59109. }
  59110. }
  59111. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  59112. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  59113. this.world.addEventListener("preStep", impostor.beforeStep);
  59114. this.world.addEventListener("postStep", impostor.afterStep);
  59115. impostor.physicsBody.addShape(shape);
  59116. this.world.add(impostor.physicsBody);
  59117. //try to keep the body moving in the right direction by taking old properties.
  59118. //Should be tested!
  59119. if (oldBody) {
  59120. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  59121. impostor.physicsBody[param].copy(oldBody[param]);
  59122. });
  59123. }
  59124. this._processChildMeshes(impostor);
  59125. }
  59126. //now update the body's transformation
  59127. this._updatePhysicsBodyTransformation(impostor);
  59128. };
  59129. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  59130. var _this = this;
  59131. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  59132. if (meshChildren.length) {
  59133. var processMesh = function (localPosition, mesh) {
  59134. var childImpostor = mesh.getPhysicsImpostor();
  59135. if (childImpostor) {
  59136. var parent = childImpostor.parent;
  59137. if (parent !== mainImpostor) {
  59138. var localPosition = mesh.position;
  59139. if (childImpostor.physicsBody) {
  59140. _this.removePhysicsBody(childImpostor);
  59141. childImpostor.physicsBody = null;
  59142. }
  59143. childImpostor.parent = mainImpostor;
  59144. childImpostor.resetUpdateFlags();
  59145. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  59146. //Add the mass of the children.
  59147. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  59148. }
  59149. }
  59150. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  59151. };
  59152. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  59153. }
  59154. };
  59155. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  59156. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  59157. this.world.removeEventListener("preStep", impostor.beforeStep);
  59158. this.world.removeEventListener("postStep", impostor.afterStep);
  59159. this.world.remove(impostor.physicsBody);
  59160. };
  59161. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  59162. var mainBody = impostorJoint.mainImpostor.physicsBody;
  59163. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  59164. if (!mainBody || !connectedBody) {
  59165. return;
  59166. }
  59167. var constraint;
  59168. var jointData = impostorJoint.joint.jointData;
  59169. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  59170. var constraintData = {
  59171. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  59172. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  59173. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  59174. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  59175. maxForce: jointData.nativeParams.maxForce,
  59176. collideConnected: !!jointData.collision
  59177. };
  59178. switch (impostorJoint.joint.type) {
  59179. case BABYLON.PhysicsJoint.HingeJoint:
  59180. case BABYLON.PhysicsJoint.Hinge2Joint:
  59181. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  59182. break;
  59183. case BABYLON.PhysicsJoint.DistanceJoint:
  59184. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  59185. break;
  59186. case BABYLON.PhysicsJoint.SpringJoint:
  59187. var springData = jointData;
  59188. constraint = new CANNON.Spring(mainBody, connectedBody, {
  59189. restLength: springData.length,
  59190. stiffness: springData.stiffness,
  59191. damping: springData.damping,
  59192. localAnchorA: constraintData.pivotA,
  59193. localAnchorB: constraintData.pivotB
  59194. });
  59195. break;
  59196. case BABYLON.PhysicsJoint.LockJoint:
  59197. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  59198. break;
  59199. case BABYLON.PhysicsJoint.PointToPointJoint:
  59200. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  59201. default:
  59202. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  59203. break;
  59204. }
  59205. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  59206. constraint.collideConnected = !!jointData.collision;
  59207. impostorJoint.joint.physicsJoint = constraint;
  59208. //don't add spring as constraint, as it is not one.
  59209. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  59210. this.world.addConstraint(constraint);
  59211. }
  59212. else {
  59213. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  59214. constraint.applyForce();
  59215. });
  59216. }
  59217. };
  59218. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  59219. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  59220. };
  59221. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  59222. var index;
  59223. var mat;
  59224. for (index = 0; index < this._physicsMaterials.length; index++) {
  59225. mat = this._physicsMaterials[index];
  59226. if (mat.friction === friction && mat.restitution === restitution) {
  59227. return mat;
  59228. }
  59229. }
  59230. var currentMat = new CANNON.Material(name);
  59231. currentMat.friction = friction;
  59232. currentMat.restitution = restitution;
  59233. this._physicsMaterials.push(currentMat);
  59234. return currentMat;
  59235. };
  59236. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  59237. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  59238. };
  59239. CannonJSPlugin.prototype._createShape = function (impostor) {
  59240. var object = impostor.object;
  59241. var returnValue;
  59242. var extendSize = impostor.getObjectExtendSize();
  59243. switch (impostor.type) {
  59244. case BABYLON.PhysicsImpostor.SphereImpostor:
  59245. var radiusX = extendSize.x;
  59246. var radiusY = extendSize.y;
  59247. var radiusZ = extendSize.z;
  59248. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  59249. break;
  59250. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  59251. case BABYLON.PhysicsImpostor.CylinderImpostor:
  59252. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  59253. break;
  59254. case BABYLON.PhysicsImpostor.BoxImpostor:
  59255. var box = extendSize.scale(0.5);
  59256. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  59257. break;
  59258. case BABYLON.PhysicsImpostor.PlaneImpostor:
  59259. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  59260. returnValue = new CANNON.Plane();
  59261. break;
  59262. case BABYLON.PhysicsImpostor.MeshImpostor:
  59263. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  59264. var rawFaces = object.getIndices ? object.getIndices() : [];
  59265. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  59266. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  59267. break;
  59268. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  59269. returnValue = this._createHeightmap(object);
  59270. break;
  59271. case BABYLON.PhysicsImpostor.ParticleImpostor:
  59272. returnValue = new CANNON.Particle();
  59273. break;
  59274. }
  59275. return returnValue;
  59276. };
  59277. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  59278. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59279. var matrix = [];
  59280. //For now pointDepth will not be used and will be automatically calculated.
  59281. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  59282. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  59283. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  59284. var elementSize = dim * 2 / arraySize;
  59285. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  59286. for (var i = 0; i < pos.length; i = i + 3) {
  59287. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  59288. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  59289. var y = pos[i + 1] + minY;
  59290. if (!matrix[x]) {
  59291. matrix[x] = [];
  59292. }
  59293. if (!matrix[x][z]) {
  59294. matrix[x][z] = y;
  59295. }
  59296. matrix[x][z] = Math.max(y, matrix[x][z]);
  59297. }
  59298. for (var x = 0; x <= arraySize; ++x) {
  59299. if (!matrix[x]) {
  59300. var loc = 1;
  59301. while (!matrix[(x + loc) % arraySize]) {
  59302. loc++;
  59303. }
  59304. matrix[x] = matrix[(x + loc) % arraySize].slice();
  59305. //console.log("missing x", x);
  59306. }
  59307. for (var z = 0; z <= arraySize; ++z) {
  59308. if (!matrix[x][z]) {
  59309. var loc = 1;
  59310. var newValue;
  59311. while (newValue === undefined) {
  59312. newValue = matrix[x][(z + loc++) % arraySize];
  59313. }
  59314. matrix[x][z] = newValue;
  59315. }
  59316. }
  59317. }
  59318. var shape = new CANNON.Heightfield(matrix, {
  59319. elementSize: elementSize
  59320. });
  59321. //For future reference, needed for body transformation
  59322. shape.minY = minY;
  59323. return shape;
  59324. };
  59325. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  59326. var object = impostor.object;
  59327. //make sure it is updated...
  59328. object.computeWorldMatrix && object.computeWorldMatrix(true);
  59329. // The delta between the mesh position and the mesh bounding box center
  59330. var center = impostor.getObjectCenter();
  59331. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  59332. this._tmpPosition.copyFrom(center);
  59333. var quaternion = object.rotationQuaternion;
  59334. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  59335. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  59336. //-90 DEG in X, precalculated
  59337. quaternion = quaternion.multiply(this._minus90X);
  59338. //Invert! (Precalculated, 90 deg in X)
  59339. //No need to clone. this will never change.
  59340. impostor.setDeltaRotation(this._plus90X);
  59341. }
  59342. //If it is a heightfield, if should be centered.
  59343. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  59344. var mesh = object;
  59345. //calculate the correct body position:
  59346. var rotationQuaternion = mesh.rotationQuaternion;
  59347. mesh.rotationQuaternion = this._tmpUnityRotation;
  59348. mesh.computeWorldMatrix(true);
  59349. //get original center with no rotation
  59350. var c = center.clone();
  59351. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  59352. //rotation is back
  59353. mesh.rotationQuaternion = rotationQuaternion;
  59354. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  59355. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  59356. mesh.setPivotMatrix(p);
  59357. mesh.computeWorldMatrix(true);
  59358. //calculate the translation
  59359. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  59360. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  59361. //add it inverted to the delta
  59362. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  59363. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  59364. mesh.setPivotMatrix(oldPivot);
  59365. mesh.computeWorldMatrix(true);
  59366. }
  59367. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  59368. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  59369. this._tmpPosition.copyFrom(object.position);
  59370. }
  59371. impostor.setDeltaPosition(this._tmpDeltaPosition);
  59372. //Now update the impostor object
  59373. impostor.physicsBody.position.copy(this._tmpPosition);
  59374. impostor.physicsBody.quaternion.copy(quaternion);
  59375. };
  59376. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  59377. impostor.object.position.copyFrom(impostor.physicsBody.position);
  59378. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  59379. };
  59380. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  59381. impostor.physicsBody.position.copy(newPosition);
  59382. impostor.physicsBody.quaternion.copy(newRotation);
  59383. };
  59384. CannonJSPlugin.prototype.isSupported = function () {
  59385. return window.CANNON !== undefined;
  59386. };
  59387. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  59388. impostor.physicsBody.velocity.copy(velocity);
  59389. };
  59390. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  59391. impostor.physicsBody.angularVelocity.copy(velocity);
  59392. };
  59393. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  59394. var v = impostor.physicsBody.velocity;
  59395. if (!v)
  59396. return null;
  59397. return new BABYLON.Vector3(v.x, v.y, v.z);
  59398. };
  59399. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  59400. var v = impostor.physicsBody.angularVelocity;
  59401. if (!v)
  59402. return null;
  59403. return new BABYLON.Vector3(v.x, v.y, v.z);
  59404. };
  59405. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  59406. impostor.physicsBody.mass = mass;
  59407. impostor.physicsBody.updateMassProperties();
  59408. };
  59409. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  59410. return impostor.physicsBody.mass;
  59411. };
  59412. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  59413. return impostor.physicsBody.material.friction;
  59414. };
  59415. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  59416. impostor.physicsBody.material.friction = friction;
  59417. };
  59418. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  59419. return impostor.physicsBody.material.restitution;
  59420. };
  59421. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  59422. impostor.physicsBody.material.restitution = restitution;
  59423. };
  59424. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  59425. impostor.physicsBody.sleep();
  59426. };
  59427. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  59428. impostor.physicsBody.wakeUp();
  59429. };
  59430. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  59431. joint.physicsJoint.distance = maxDistance;
  59432. };
  59433. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  59434. if (!motorIndex) {
  59435. joint.physicsJoint.enableMotor();
  59436. }
  59437. };
  59438. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  59439. if (!motorIndex) {
  59440. joint.physicsJoint.disableMotor();
  59441. }
  59442. };
  59443. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  59444. if (!motorIndex) {
  59445. joint.physicsJoint.enableMotor();
  59446. joint.physicsJoint.setMotorSpeed(speed);
  59447. if (maxForce) {
  59448. this.setLimit(joint, maxForce);
  59449. }
  59450. }
  59451. };
  59452. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  59453. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  59454. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  59455. };
  59456. CannonJSPlugin.prototype._getDebugMaterial = function (scene) {
  59457. if (!this._debugMaterial) {
  59458. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  59459. this._debugMaterial.wireframe = true;
  59460. }
  59461. return this._debugMaterial;
  59462. };
  59463. CannonJSPlugin.prototype._getDebugBoxMesh = function (scene) {
  59464. if (!this._debugBoxMesh) {
  59465. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  59466. this._debugBoxMesh.renderingGroupId = 1;
  59467. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59468. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  59469. scene.removeMesh(this._debugBoxMesh);
  59470. }
  59471. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  59472. };
  59473. CannonJSPlugin.prototype._getDebugSphereMesh = function (scene) {
  59474. if (!this._debugSphereMesh) {
  59475. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  59476. this._debugSphereMesh.renderingGroupId = 1;
  59477. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59478. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  59479. scene.removeMesh(this._debugSphereMesh);
  59480. }
  59481. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  59482. };
  59483. CannonJSPlugin.prototype.getDebugMesh = function (impostor, scene) {
  59484. var body = impostor.physicsBody;
  59485. var shape = body.shapes[0];
  59486. var mesh;
  59487. if (shape.halfExtents) {
  59488. mesh = this._getDebugBoxMesh(scene);
  59489. mesh.scaling.x = shape.halfExtents.x * 2;
  59490. mesh.scaling.y = shape.halfExtents.y * 2;
  59491. mesh.scaling.z = shape.halfExtents.z * 2;
  59492. }
  59493. else if (shape.boundingSphereRadius) {
  59494. mesh = this._getDebugSphereMesh(scene);
  59495. mesh.scaling.x = shape.boundingSphereRadius * 2;
  59496. mesh.scaling.y = shape.boundingSphereRadius * 2;
  59497. mesh.scaling.z = shape.boundingSphereRadius * 2;
  59498. }
  59499. return mesh;
  59500. };
  59501. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  59502. var body = impostor.physicsBody;
  59503. mesh.position.x = body.position.x;
  59504. mesh.position.y = body.position.y;
  59505. mesh.position.z = body.position.z;
  59506. mesh.rotationQuaternion.x = body.quaternion.x;
  59507. mesh.rotationQuaternion.y = body.quaternion.y;
  59508. mesh.rotationQuaternion.z = body.quaternion.z;
  59509. mesh.rotationQuaternion.w = body.quaternion.w;
  59510. };
  59511. CannonJSPlugin.prototype.dispose = function () {
  59512. if (this._debugBoxMesh) {
  59513. this._debugBoxMesh.dispose();
  59514. }
  59515. if (this._debugSphereMesh) {
  59516. this._debugSphereMesh.dispose();
  59517. }
  59518. if (this._debugMaterial) {
  59519. this._debugMaterial.dispose();
  59520. }
  59521. };
  59522. return CannonJSPlugin;
  59523. }());
  59524. BABYLON.CannonJSPlugin = CannonJSPlugin;
  59525. })(BABYLON || (BABYLON = {}));
  59526. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  59527. var BABYLON;
  59528. (function (BABYLON) {
  59529. var OimoJSPlugin = (function () {
  59530. function OimoJSPlugin(iterations) {
  59531. this.name = "OimoJSPlugin";
  59532. this._tmpImpostorsArray = [];
  59533. this._tmpPositionVector = BABYLON.Vector3.Zero();
  59534. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  59535. this.world.worldscale(1);
  59536. this.world.clear();
  59537. //making sure no stats are calculated
  59538. this.world.isNoStat = true;
  59539. }
  59540. OimoJSPlugin.prototype.setGravity = function (gravity) {
  59541. this.world.gravity.copy(gravity);
  59542. };
  59543. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  59544. this.world.timeStep = timeStep;
  59545. };
  59546. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  59547. var _this = this;
  59548. impostors.forEach(function (impostor) {
  59549. impostor.beforeStep();
  59550. });
  59551. this.world.step();
  59552. impostors.forEach(function (impostor) {
  59553. impostor.afterStep();
  59554. //update the ordered impostors array
  59555. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  59556. });
  59557. //check for collisions
  59558. var contact = this.world.contacts;
  59559. while (contact !== null) {
  59560. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  59561. contact = contact.next;
  59562. continue;
  59563. }
  59564. //is this body colliding with any other? get the impostor
  59565. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  59566. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  59567. if (!mainImpostor || !collidingImpostor) {
  59568. contact = contact.next;
  59569. continue;
  59570. }
  59571. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  59572. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  59573. contact = contact.next;
  59574. }
  59575. };
  59576. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  59577. var mass = impostor.physicsBody.massInfo.mass;
  59578. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  59579. };
  59580. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  59581. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  59582. this.applyImpulse(impostor, force, contactPoint);
  59583. };
  59584. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  59585. var _this = this;
  59586. //parent-child relationship. Does this impostor has a parent impostor?
  59587. if (impostor.parent) {
  59588. if (impostor.physicsBody) {
  59589. this.removePhysicsBody(impostor);
  59590. //TODO is that needed?
  59591. impostor.forceUpdate();
  59592. }
  59593. return;
  59594. }
  59595. if (impostor.isBodyInitRequired()) {
  59596. var bodyConfig = {
  59597. name: impostor.uniqueId,
  59598. //Oimo must have mass, also for static objects.
  59599. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  59600. size: [],
  59601. type: [],
  59602. pos: [],
  59603. rot: [],
  59604. move: impostor.getParam("mass") !== 0,
  59605. //Supporting older versions of Oimo
  59606. world: this.world
  59607. };
  59608. var impostors = [impostor];
  59609. var addToArray = function (parent) {
  59610. if (!parent.getChildMeshes)
  59611. return;
  59612. parent.getChildMeshes().forEach(function (m) {
  59613. if (m.physicsImpostor) {
  59614. impostors.push(m.physicsImpostor);
  59615. m.physicsImpostor._init();
  59616. }
  59617. });
  59618. };
  59619. addToArray(impostor.object);
  59620. var checkWithEpsilon_1 = function (value) {
  59621. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  59622. };
  59623. impostors.forEach(function (i) {
  59624. //get the correct bounding box
  59625. var oldQuaternion = i.object.rotationQuaternion;
  59626. var rot = new OIMO.Euler().setFromQuaternion({
  59627. x: impostor.object.rotationQuaternion.x,
  59628. y: impostor.object.rotationQuaternion.y,
  59629. z: impostor.object.rotationQuaternion.z,
  59630. s: impostor.object.rotationQuaternion.w
  59631. });
  59632. var extendSize = i.getObjectExtendSize();
  59633. if (i === impostor) {
  59634. var center = impostor.getObjectCenter();
  59635. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  59636. //Can also use Array.prototype.push.apply
  59637. bodyConfig.pos.push(center.x);
  59638. bodyConfig.pos.push(center.y);
  59639. bodyConfig.pos.push(center.z);
  59640. //tmp solution
  59641. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  59642. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  59643. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  59644. }
  59645. else {
  59646. bodyConfig.pos.push(i.object.position.x);
  59647. bodyConfig.pos.push(i.object.position.y);
  59648. bodyConfig.pos.push(i.object.position.z);
  59649. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  59650. bodyConfig.rot.push(0);
  59651. bodyConfig.rot.push(0);
  59652. bodyConfig.rot.push(0);
  59653. }
  59654. // register mesh
  59655. switch (i.type) {
  59656. case BABYLON.PhysicsImpostor.ParticleImpostor:
  59657. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  59658. case BABYLON.PhysicsImpostor.SphereImpostor:
  59659. var radiusX = extendSize.x;
  59660. var radiusY = extendSize.y;
  59661. var radiusZ = extendSize.z;
  59662. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  59663. bodyConfig.type.push('sphere');
  59664. //due to the way oimo works with compounds, add 3 times
  59665. bodyConfig.size.push(size);
  59666. bodyConfig.size.push(size);
  59667. bodyConfig.size.push(size);
  59668. break;
  59669. case BABYLON.PhysicsImpostor.CylinderImpostor:
  59670. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  59671. var sizeY = checkWithEpsilon_1(extendSize.y);
  59672. bodyConfig.type.push('cylinder');
  59673. bodyConfig.size.push(sizeX);
  59674. bodyConfig.size.push(sizeY);
  59675. //due to the way oimo works with compounds, add one more value.
  59676. bodyConfig.size.push(sizeY);
  59677. break;
  59678. case BABYLON.PhysicsImpostor.PlaneImpostor:
  59679. case BABYLON.PhysicsImpostor.BoxImpostor:
  59680. default:
  59681. var sizeX = checkWithEpsilon_1(extendSize.x);
  59682. var sizeY = checkWithEpsilon_1(extendSize.y);
  59683. var sizeZ = checkWithEpsilon_1(extendSize.z);
  59684. bodyConfig.type.push('box');
  59685. bodyConfig.size.push(sizeX);
  59686. bodyConfig.size.push(sizeY);
  59687. bodyConfig.size.push(sizeZ);
  59688. break;
  59689. }
  59690. //actually not needed, but hey...
  59691. i.object.rotationQuaternion = oldQuaternion;
  59692. });
  59693. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  59694. }
  59695. else {
  59696. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  59697. }
  59698. impostor.setDeltaPosition(this._tmpPositionVector);
  59699. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  59700. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  59701. };
  59702. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  59703. //impostor.physicsBody.dispose();
  59704. //Same as : (older oimo versions)
  59705. this.world.removeRigidBody(impostor.physicsBody);
  59706. };
  59707. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  59708. var mainBody = impostorJoint.mainImpostor.physicsBody;
  59709. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  59710. if (!mainBody || !connectedBody) {
  59711. return;
  59712. }
  59713. var jointData = impostorJoint.joint.jointData;
  59714. var options = jointData.nativeParams || {};
  59715. var type;
  59716. var nativeJointData = {
  59717. body1: mainBody,
  59718. body2: connectedBody,
  59719. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  59720. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  59721. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  59722. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  59723. min: options.min,
  59724. max: options.max,
  59725. collision: options.collision || jointData.collision,
  59726. spring: options.spring,
  59727. //supporting older version of Oimo
  59728. world: this.world
  59729. };
  59730. switch (impostorJoint.joint.type) {
  59731. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  59732. type = "jointBall";
  59733. break;
  59734. case BABYLON.PhysicsJoint.SpringJoint:
  59735. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  59736. var springData = jointData;
  59737. nativeJointData.min = springData.length || nativeJointData.min;
  59738. //Max should also be set, just make sure it is at least min
  59739. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  59740. case BABYLON.PhysicsJoint.DistanceJoint:
  59741. type = "jointDistance";
  59742. nativeJointData.max = jointData.maxDistance;
  59743. break;
  59744. case BABYLON.PhysicsJoint.PrismaticJoint:
  59745. type = "jointPrisme";
  59746. break;
  59747. case BABYLON.PhysicsJoint.SliderJoint:
  59748. type = "jointSlide";
  59749. break;
  59750. case BABYLON.PhysicsJoint.WheelJoint:
  59751. type = "jointWheel";
  59752. break;
  59753. case BABYLON.PhysicsJoint.HingeJoint:
  59754. default:
  59755. type = "jointHinge";
  59756. break;
  59757. }
  59758. nativeJointData.type = type;
  59759. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  59760. };
  59761. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  59762. //Bug in Oimo prevents us from disposing a joint in the playground
  59763. //joint.joint.physicsJoint.dispose();
  59764. //So we will bruteforce it!
  59765. try {
  59766. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  59767. }
  59768. catch (e) {
  59769. BABYLON.Tools.Warn(e);
  59770. }
  59771. };
  59772. OimoJSPlugin.prototype.isSupported = function () {
  59773. return OIMO !== undefined;
  59774. };
  59775. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  59776. if (!impostor.physicsBody.sleeping) {
  59777. //TODO check that
  59778. if (impostor.physicsBody.shapes.next) {
  59779. var parentShape = this._getLastShape(impostor.physicsBody);
  59780. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  59781. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  59782. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  59783. }
  59784. else {
  59785. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  59786. }
  59787. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  59788. impostor.object.rotationQuaternion.normalize();
  59789. }
  59790. };
  59791. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  59792. var body = impostor.physicsBody;
  59793. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  59794. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  59795. body.syncShapes();
  59796. body.awake();
  59797. };
  59798. OimoJSPlugin.prototype._getLastShape = function (body) {
  59799. var lastShape = body.shapes;
  59800. while (lastShape.next) {
  59801. lastShape = lastShape.next;
  59802. }
  59803. return lastShape;
  59804. };
  59805. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  59806. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  59807. };
  59808. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  59809. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  59810. };
  59811. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  59812. var v = impostor.physicsBody.linearVelocity;
  59813. if (!v)
  59814. return null;
  59815. return new BABYLON.Vector3(v.x, v.y, v.z);
  59816. };
  59817. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  59818. var v = impostor.physicsBody.angularVelocity;
  59819. if (!v)
  59820. return null;
  59821. return new BABYLON.Vector3(v.x, v.y, v.z);
  59822. };
  59823. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  59824. var staticBody = mass === 0;
  59825. //this will actually set the body's density and not its mass.
  59826. //But this is how oimo treats the mass variable.
  59827. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  59828. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  59829. };
  59830. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  59831. return impostor.physicsBody.shapes.density;
  59832. };
  59833. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  59834. return impostor.physicsBody.shapes.friction;
  59835. };
  59836. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  59837. impostor.physicsBody.shapes.friction = friction;
  59838. };
  59839. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  59840. return impostor.physicsBody.shapes.restitution;
  59841. };
  59842. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  59843. impostor.physicsBody.shapes.restitution = restitution;
  59844. };
  59845. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  59846. impostor.physicsBody.sleep();
  59847. };
  59848. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  59849. impostor.physicsBody.awake();
  59850. };
  59851. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  59852. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  59853. if (minDistance !== void 0) {
  59854. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  59855. }
  59856. };
  59857. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  59858. //TODO separate rotational and transational motors.
  59859. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  59860. if (motor) {
  59861. motor.setMotor(speed, maxForce);
  59862. }
  59863. };
  59864. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  59865. //TODO separate rotational and transational motors.
  59866. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  59867. if (motor) {
  59868. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  59869. }
  59870. };
  59871. OimoJSPlugin.prototype._getDebugMaterial = function (scene) {
  59872. if (!this._debugMaterial) {
  59873. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  59874. this._debugMaterial.wireframe = true;
  59875. }
  59876. return this._debugMaterial;
  59877. };
  59878. OimoJSPlugin.prototype._getDebugBoxMesh = function (scene) {
  59879. if (!this._debugBoxMesh) {
  59880. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  59881. this._debugBoxMesh.renderingGroupId = 1;
  59882. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59883. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  59884. scene.removeMesh(this._debugBoxMesh);
  59885. }
  59886. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  59887. };
  59888. OimoJSPlugin.prototype._getDebugSphereMesh = function (scene) {
  59889. if (!this._debugSphereMesh) {
  59890. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  59891. this._debugSphereMesh.renderingGroupId = 1;
  59892. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59893. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  59894. scene.removeMesh(this._debugSphereMesh);
  59895. }
  59896. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  59897. };
  59898. OimoJSPlugin.prototype.getDebugMesh = function (impostor, scene) {
  59899. var body = impostor.physicsBody;
  59900. var shape = body.shapes;
  59901. var mesh;
  59902. if (shape.halfWidth) {
  59903. mesh = this._getDebugBoxMesh(scene);
  59904. mesh.scaling.x = shape.halfWidth * 2;
  59905. mesh.scaling.y = shape.halfHeight * 2;
  59906. mesh.scaling.z = shape.halfDepth * 2;
  59907. }
  59908. else if (shape.radius) {
  59909. mesh = this._getDebugSphereMesh(scene);
  59910. mesh.scaling.x = shape.radius * 2;
  59911. mesh.scaling.y = shape.radius * 2;
  59912. mesh.scaling.z = shape.radius * 2;
  59913. }
  59914. return mesh;
  59915. };
  59916. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  59917. var body = impostor.physicsBody;
  59918. mesh.position.x = body.position.x;
  59919. mesh.position.y = body.position.y;
  59920. mesh.position.z = body.position.z;
  59921. mesh.rotationQuaternion.x = body.orientation.x;
  59922. mesh.rotationQuaternion.y = body.orientation.y;
  59923. mesh.rotationQuaternion.z = body.orientation.z;
  59924. mesh.rotationQuaternion.w = body.orientation.s;
  59925. };
  59926. OimoJSPlugin.prototype.dispose = function () {
  59927. if (this._debugBoxMesh) {
  59928. this._debugBoxMesh.dispose();
  59929. }
  59930. if (this._debugSphereMesh) {
  59931. this._debugSphereMesh.dispose();
  59932. }
  59933. if (this._debugMaterial) {
  59934. this._debugMaterial.dispose();
  59935. }
  59936. this.world.clear();
  59937. };
  59938. return OimoJSPlugin;
  59939. }());
  59940. BABYLON.OimoJSPlugin = OimoJSPlugin;
  59941. })(BABYLON || (BABYLON = {}));
  59942. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  59943. var BABYLON;
  59944. (function (BABYLON) {
  59945. var Internals;
  59946. (function (Internals) {
  59947. /*
  59948. * Based on jsTGALoader - Javascript loader for TGA file
  59949. * By Vincent Thibault
  59950. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  59951. */
  59952. var TGATools = (function () {
  59953. function TGATools() {
  59954. }
  59955. TGATools.GetTGAHeader = function (data) {
  59956. var offset = 0;
  59957. var header = {
  59958. id_length: data[offset++],
  59959. colormap_type: data[offset++],
  59960. image_type: data[offset++],
  59961. colormap_index: data[offset++] | data[offset++] << 8,
  59962. colormap_length: data[offset++] | data[offset++] << 8,
  59963. colormap_size: data[offset++],
  59964. origin: [
  59965. data[offset++] | data[offset++] << 8,
  59966. data[offset++] | data[offset++] << 8
  59967. ],
  59968. width: data[offset++] | data[offset++] << 8,
  59969. height: data[offset++] | data[offset++] << 8,
  59970. pixel_size: data[offset++],
  59971. flags: data[offset++]
  59972. };
  59973. return header;
  59974. };
  59975. TGATools.UploadContent = function (gl, data) {
  59976. // Not enough data to contain header ?
  59977. if (data.length < 19) {
  59978. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  59979. return;
  59980. }
  59981. // Read Header
  59982. var offset = 18;
  59983. var header = TGATools.GetTGAHeader(data);
  59984. // Assume it's a valid Targa file.
  59985. if (header.id_length + offset > data.length) {
  59986. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  59987. return;
  59988. }
  59989. // Skip not needed data
  59990. offset += header.id_length;
  59991. var use_rle = false;
  59992. var use_pal = false;
  59993. var use_rgb = false;
  59994. var use_grey = false;
  59995. // Get some informations.
  59996. switch (header.image_type) {
  59997. case TGATools._TYPE_RLE_INDEXED:
  59998. use_rle = true;
  59999. case TGATools._TYPE_INDEXED:
  60000. use_pal = true;
  60001. break;
  60002. case TGATools._TYPE_RLE_RGB:
  60003. use_rle = true;
  60004. case TGATools._TYPE_RGB:
  60005. use_rgb = true;
  60006. break;
  60007. case TGATools._TYPE_RLE_GREY:
  60008. use_rle = true;
  60009. case TGATools._TYPE_GREY:
  60010. use_grey = true;
  60011. break;
  60012. }
  60013. var pixel_data;
  60014. var numAlphaBits = header.flags & 0xf;
  60015. var pixel_size = header.pixel_size >> 3;
  60016. var pixel_total = header.width * header.height * pixel_size;
  60017. // Read palettes
  60018. var palettes;
  60019. if (use_pal) {
  60020. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  60021. }
  60022. // Read LRE
  60023. if (use_rle) {
  60024. pixel_data = new Uint8Array(pixel_total);
  60025. var c, count, i;
  60026. var localOffset = 0;
  60027. var pixels = new Uint8Array(pixel_size);
  60028. while (offset < pixel_total && localOffset < pixel_total) {
  60029. c = data[offset++];
  60030. count = (c & 0x7f) + 1;
  60031. // RLE pixels
  60032. if (c & 0x80) {
  60033. // Bind pixel tmp array
  60034. for (i = 0; i < pixel_size; ++i) {
  60035. pixels[i] = data[offset++];
  60036. }
  60037. // Copy pixel array
  60038. for (i = 0; i < count; ++i) {
  60039. pixel_data.set(pixels, localOffset + i * pixel_size);
  60040. }
  60041. localOffset += pixel_size * count;
  60042. }
  60043. else {
  60044. count *= pixel_size;
  60045. for (i = 0; i < count; ++i) {
  60046. pixel_data[localOffset + i] = data[offset++];
  60047. }
  60048. localOffset += count;
  60049. }
  60050. }
  60051. }
  60052. else {
  60053. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  60054. }
  60055. // Load to texture
  60056. var x_start, y_start, x_step, y_step, y_end, x_end;
  60057. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  60058. default:
  60059. case TGATools._ORIGIN_UL:
  60060. x_start = 0;
  60061. x_step = 1;
  60062. x_end = header.width;
  60063. y_start = 0;
  60064. y_step = 1;
  60065. y_end = header.height;
  60066. break;
  60067. case TGATools._ORIGIN_BL:
  60068. x_start = 0;
  60069. x_step = 1;
  60070. x_end = header.width;
  60071. y_start = header.height - 1;
  60072. y_step = -1;
  60073. y_end = -1;
  60074. break;
  60075. case TGATools._ORIGIN_UR:
  60076. x_start = header.width - 1;
  60077. x_step = -1;
  60078. x_end = -1;
  60079. y_start = 0;
  60080. y_step = 1;
  60081. y_end = header.height;
  60082. break;
  60083. case TGATools._ORIGIN_BR:
  60084. x_start = header.width - 1;
  60085. x_step = -1;
  60086. x_end = -1;
  60087. y_start = header.height - 1;
  60088. y_step = -1;
  60089. y_end = -1;
  60090. break;
  60091. }
  60092. // Load the specify method
  60093. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  60094. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  60095. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  60096. };
  60097. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60098. var image = pixel_data, colormap = palettes;
  60099. var width = header.width, height = header.height;
  60100. var color, i = 0, x, y;
  60101. var imageData = new Uint8Array(width * height * 4);
  60102. for (y = y_start; y !== y_end; y += y_step) {
  60103. for (x = x_start; x !== x_end; x += x_step, i++) {
  60104. color = image[i];
  60105. imageData[(x + width * y) * 4 + 3] = 255;
  60106. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  60107. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  60108. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  60109. }
  60110. }
  60111. return imageData;
  60112. };
  60113. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60114. var image = pixel_data;
  60115. var width = header.width, height = header.height;
  60116. var color, i = 0, x, y;
  60117. var imageData = new Uint8Array(width * height * 4);
  60118. for (y = y_start; y !== y_end; y += y_step) {
  60119. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  60120. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  60121. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  60122. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  60123. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  60124. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  60125. }
  60126. }
  60127. return imageData;
  60128. };
  60129. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60130. var image = pixel_data;
  60131. var width = header.width, height = header.height;
  60132. var i = 0, x, y;
  60133. var imageData = new Uint8Array(width * height * 4);
  60134. for (y = y_start; y !== y_end; y += y_step) {
  60135. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  60136. imageData[(x + width * y) * 4 + 3] = 255;
  60137. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60138. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  60139. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  60140. }
  60141. }
  60142. return imageData;
  60143. };
  60144. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60145. var image = pixel_data;
  60146. var width = header.width, height = header.height;
  60147. var i = 0, x, y;
  60148. var imageData = new Uint8Array(width * height * 4);
  60149. for (y = y_start; y !== y_end; y += y_step) {
  60150. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  60151. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60152. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  60153. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  60154. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  60155. }
  60156. }
  60157. return imageData;
  60158. };
  60159. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60160. var image = pixel_data;
  60161. var width = header.width, height = header.height;
  60162. var color, i = 0, x, y;
  60163. var imageData = new Uint8Array(width * height * 4);
  60164. for (y = y_start; y !== y_end; y += y_step) {
  60165. for (x = x_start; x !== x_end; x += x_step, i++) {
  60166. color = image[i];
  60167. imageData[(x + width * y) * 4 + 0] = color;
  60168. imageData[(x + width * y) * 4 + 1] = color;
  60169. imageData[(x + width * y) * 4 + 2] = color;
  60170. imageData[(x + width * y) * 4 + 3] = 255;
  60171. }
  60172. }
  60173. return imageData;
  60174. };
  60175. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60176. var image = pixel_data;
  60177. var width = header.width, height = header.height;
  60178. var i = 0, x, y;
  60179. var imageData = new Uint8Array(width * height * 4);
  60180. for (y = y_start; y !== y_end; y += y_step) {
  60181. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  60182. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  60183. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  60184. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60185. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  60186. }
  60187. }
  60188. return imageData;
  60189. };
  60190. return TGATools;
  60191. }());
  60192. TGATools._TYPE_NO_DATA = 0;
  60193. TGATools._TYPE_INDEXED = 1;
  60194. TGATools._TYPE_RGB = 2;
  60195. TGATools._TYPE_GREY = 3;
  60196. TGATools._TYPE_RLE_INDEXED = 9;
  60197. TGATools._TYPE_RLE_RGB = 10;
  60198. TGATools._TYPE_RLE_GREY = 11;
  60199. TGATools._ORIGIN_MASK = 0x30;
  60200. TGATools._ORIGIN_SHIFT = 0x04;
  60201. TGATools._ORIGIN_BL = 0x00;
  60202. TGATools._ORIGIN_BR = 0x01;
  60203. TGATools._ORIGIN_UL = 0x02;
  60204. TGATools._ORIGIN_UR = 0x03;
  60205. Internals.TGATools = TGATools;
  60206. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60207. })(BABYLON || (BABYLON = {}));
  60208. //# sourceMappingURL=babylon.tga.js.map
  60209. var BABYLON;
  60210. (function (BABYLON) {
  60211. var Internals;
  60212. (function (Internals) {
  60213. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  60214. // All values and structures referenced from:
  60215. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  60216. var DDS_MAGIC = 0x20534444;
  60217. 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;
  60218. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  60219. 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;
  60220. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  60221. function FourCCToInt32(value) {
  60222. return value.charCodeAt(0) +
  60223. (value.charCodeAt(1) << 8) +
  60224. (value.charCodeAt(2) << 16) +
  60225. (value.charCodeAt(3) << 24);
  60226. }
  60227. function Int32ToFourCC(value) {
  60228. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  60229. }
  60230. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  60231. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  60232. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  60233. var headerLengthInt = 31; // The header length in 32 bit ints
  60234. // Offsets into the header array
  60235. var off_magic = 0;
  60236. var off_size = 1;
  60237. var off_flags = 2;
  60238. var off_height = 3;
  60239. var off_width = 4;
  60240. var off_mipmapCount = 7;
  60241. var off_pfFlags = 20;
  60242. var off_pfFourCC = 21;
  60243. var off_RGBbpp = 22;
  60244. var off_RMask = 23;
  60245. var off_GMask = 24;
  60246. var off_BMask = 25;
  60247. var off_AMask = 26;
  60248. var off_caps1 = 27;
  60249. var off_caps2 = 28;
  60250. ;
  60251. var DDSTools = (function () {
  60252. function DDSTools() {
  60253. }
  60254. DDSTools.GetDDSInfo = function (arrayBuffer) {
  60255. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  60256. var mipmapCount = 1;
  60257. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  60258. mipmapCount = Math.max(1, header[off_mipmapCount]);
  60259. }
  60260. return {
  60261. width: header[off_width],
  60262. height: header[off_height],
  60263. mipmapCount: mipmapCount,
  60264. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  60265. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  60266. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  60267. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  60268. };
  60269. };
  60270. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  60271. var byteArray = new Uint8Array(dataLength);
  60272. var srcData = new Uint8Array(arrayBuffer);
  60273. var index = 0;
  60274. for (var y = height - 1; y >= 0; y--) {
  60275. for (var x = 0; x < width; x++) {
  60276. var srcPos = dataOffset + (x + y * width) * 4;
  60277. byteArray[index + 2] = srcData[srcPos];
  60278. byteArray[index + 1] = srcData[srcPos + 1];
  60279. byteArray[index] = srcData[srcPos + 2];
  60280. byteArray[index + 3] = srcData[srcPos + 3];
  60281. index += 4;
  60282. }
  60283. }
  60284. return byteArray;
  60285. };
  60286. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  60287. var byteArray = new Uint8Array(dataLength);
  60288. var srcData = new Uint8Array(arrayBuffer);
  60289. var index = 0;
  60290. for (var y = height - 1; y >= 0; y--) {
  60291. for (var x = 0; x < width; x++) {
  60292. var srcPos = dataOffset + (x + y * width) * 3;
  60293. byteArray[index + 2] = srcData[srcPos];
  60294. byteArray[index + 1] = srcData[srcPos + 1];
  60295. byteArray[index] = srcData[srcPos + 2];
  60296. index += 3;
  60297. }
  60298. }
  60299. return byteArray;
  60300. };
  60301. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  60302. var byteArray = new Uint8Array(dataLength);
  60303. var srcData = new Uint8Array(arrayBuffer);
  60304. var index = 0;
  60305. for (var y = height - 1; y >= 0; y--) {
  60306. for (var x = 0; x < width; x++) {
  60307. var srcPos = dataOffset + (x + y * width);
  60308. byteArray[index] = srcData[srcPos];
  60309. index++;
  60310. }
  60311. }
  60312. return byteArray;
  60313. };
  60314. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  60315. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  60316. if (header[off_magic] != DDS_MAGIC) {
  60317. BABYLON.Tools.Error("Invalid magic number in DDS header");
  60318. return;
  60319. }
  60320. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  60321. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  60322. return;
  60323. }
  60324. if (info.isFourCC) {
  60325. fourCC = header[off_pfFourCC];
  60326. switch (fourCC) {
  60327. case FOURCC_DXT1:
  60328. blockBytes = 8;
  60329. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  60330. break;
  60331. case FOURCC_DXT3:
  60332. blockBytes = 16;
  60333. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  60334. break;
  60335. case FOURCC_DXT5:
  60336. blockBytes = 16;
  60337. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  60338. break;
  60339. default:
  60340. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  60341. return;
  60342. }
  60343. }
  60344. mipmapCount = 1;
  60345. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  60346. mipmapCount = Math.max(1, header[off_mipmapCount]);
  60347. }
  60348. var bpp = header[off_RGBbpp];
  60349. for (var face = 0; face < faces; face++) {
  60350. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  60351. width = header[off_width];
  60352. height = header[off_height];
  60353. dataOffset = header[off_size] + 4;
  60354. for (i = 0; i < mipmapCount; ++i) {
  60355. if (info.isRGB) {
  60356. if (bpp === 24) {
  60357. dataLength = width * height * 3;
  60358. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  60359. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  60360. }
  60361. else {
  60362. dataLength = width * height * 4;
  60363. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  60364. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  60365. }
  60366. }
  60367. else if (info.isLuminance) {
  60368. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  60369. var unpaddedRowSize = width;
  60370. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  60371. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  60372. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  60373. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  60374. }
  60375. else {
  60376. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  60377. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  60378. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  60379. }
  60380. dataOffset += dataLength;
  60381. width *= 0.5;
  60382. height *= 0.5;
  60383. width = Math.max(1.0, width);
  60384. height = Math.max(1.0, height);
  60385. }
  60386. }
  60387. };
  60388. return DDSTools;
  60389. }());
  60390. Internals.DDSTools = DDSTools;
  60391. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60392. })(BABYLON || (BABYLON = {}));
  60393. //# sourceMappingURL=babylon.dds.js.map
  60394. var BABYLON;
  60395. (function (BABYLON) {
  60396. var Internals;
  60397. (function (Internals) {
  60398. /**
  60399. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  60400. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  60401. */
  60402. var KhronosTextureContainer = (function () {
  60403. /**
  60404. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  60405. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  60406. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  60407. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  60408. */
  60409. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  60410. this.arrayBuffer = arrayBuffer;
  60411. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  60412. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  60413. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  60414. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  60415. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  60416. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  60417. BABYLON.Tools.Error("texture missing KTX identifier");
  60418. return;
  60419. }
  60420. // load the reset of the header in native 32 bit int
  60421. var header = new Int32Array(this.arrayBuffer, 12, 13);
  60422. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  60423. var oppositeEndianess = header[0] === 0x01020304;
  60424. // read all the header elements in order they exist in the file, without modification (sans endainness)
  60425. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  60426. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  60427. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  60428. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  60429. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  60430. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  60431. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  60432. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  60433. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  60434. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  60435. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  60436. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  60437. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  60438. if (this.glType !== 0) {
  60439. BABYLON.Tools.Error("only compressed formats currently supported");
  60440. return;
  60441. }
  60442. else {
  60443. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  60444. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  60445. }
  60446. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  60447. BABYLON.Tools.Error("only 2D textures currently supported");
  60448. return;
  60449. }
  60450. if (this.numberOfArrayElements !== 0) {
  60451. BABYLON.Tools.Error("texture arrays not currently supported");
  60452. return;
  60453. }
  60454. if (this.numberOfFaces !== facesExpected) {
  60455. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  60456. return;
  60457. }
  60458. // we now have a completely validated file, so could use existence of loadType as success
  60459. // would need to make this more elaborate & adjust checks above to support more than one load type
  60460. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  60461. }
  60462. // not as fast hardware based, but will probably never need to use
  60463. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  60464. return ((val & 0xFF) << 24)
  60465. | ((val & 0xFF00) << 8)
  60466. | ((val >> 8) & 0xFF00)
  60467. | ((val >> 24) & 0xFF);
  60468. };
  60469. /**
  60470. * It is assumed that the texture has already been created & is currently bound
  60471. */
  60472. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  60473. switch (this.loadType) {
  60474. case KhronosTextureContainer.COMPRESSED_2D:
  60475. this._upload2DCompressedLevels(gl, loadMipmaps);
  60476. break;
  60477. case KhronosTextureContainer.TEX_2D:
  60478. case KhronosTextureContainer.COMPRESSED_3D:
  60479. case KhronosTextureContainer.TEX_3D:
  60480. }
  60481. };
  60482. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  60483. // initialize width & height for level 1
  60484. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  60485. var width = this.pixelWidth;
  60486. var height = this.pixelHeight;
  60487. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  60488. for (var level = 0; level < mipmapCount; level++) {
  60489. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  60490. for (var face = 0; face < this.numberOfFaces; face++) {
  60491. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  60492. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  60493. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  60494. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  60495. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  60496. }
  60497. width = Math.max(1.0, width * 0.5);
  60498. height = Math.max(1.0, height * 0.5);
  60499. }
  60500. };
  60501. return KhronosTextureContainer;
  60502. }());
  60503. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  60504. // load types
  60505. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  60506. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  60507. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  60508. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  60509. Internals.KhronosTextureContainer = KhronosTextureContainer;
  60510. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60511. })(BABYLON || (BABYLON = {}));
  60512. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  60513. var BABYLON;
  60514. (function (BABYLON) {
  60515. var DynamicFloatArrayElementInfo = (function () {
  60516. function DynamicFloatArrayElementInfo() {
  60517. }
  60518. return DynamicFloatArrayElementInfo;
  60519. }());
  60520. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  60521. /**
  60522. * 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.
  60523. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  60524. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  60525. * 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.
  60526. * 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.
  60527. * 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".
  60528. */
  60529. var DynamicFloatArray = (function () {
  60530. /**
  60531. * Construct an instance of the dynamic float array
  60532. * @param stride size of one element in float (i.e. not bytes!)
  60533. * @param initialElementCount the number of available entries at construction
  60534. */
  60535. function DynamicFloatArray(stride, initialElementCount) {
  60536. this.compareValueOffset = null;
  60537. this.sortingAscending = true;
  60538. this._stride = stride;
  60539. this.buffer = new Float32Array(stride * initialElementCount);
  60540. this._lastUsed = 0;
  60541. this._firstFree = 0;
  60542. this._allEntries = new Array(initialElementCount);
  60543. this._freeEntries = new Array(initialElementCount);
  60544. for (var i = 0; i < initialElementCount; i++) {
  60545. var element = new DynamicFloatArrayElementInfo();
  60546. element.offset = i * stride;
  60547. this._allEntries[i] = element;
  60548. this._freeEntries[initialElementCount - i - 1] = element;
  60549. }
  60550. }
  60551. /**
  60552. * Allocate an element in the array.
  60553. * @return the element info instance that contains the offset into the main buffer of the element's location.
  60554. * Beware, this offset may change when you call pack()
  60555. */
  60556. DynamicFloatArray.prototype.allocElement = function () {
  60557. if (this._freeEntries.length === 0) {
  60558. this._growBuffer();
  60559. }
  60560. var el = this._freeEntries.pop();
  60561. this._lastUsed = Math.max(el.offset, this._lastUsed);
  60562. if (el.offset === this._firstFree) {
  60563. if (this._freeEntries.length > 0) {
  60564. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  60565. }
  60566. else {
  60567. this._firstFree += this._stride;
  60568. }
  60569. }
  60570. return el;
  60571. };
  60572. /**
  60573. * Free the element corresponding to the given element info
  60574. * @param elInfo the element that describe the allocated element
  60575. */
  60576. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  60577. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  60578. this._freeEntries.push(elInfo);
  60579. };
  60580. /**
  60581. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  60582. * 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().
  60583. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  60584. */
  60585. DynamicFloatArray.prototype.pack = function () {
  60586. // no free slot? no need to pack
  60587. if (this._freeEntries.length === 0) {
  60588. return this.buffer;
  60589. }
  60590. // If the buffer is already packed the last used will always be lower than the first free
  60591. // 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.
  60592. if (this._lastUsed < this._firstFree) {
  60593. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  60594. return elementsBuffer_1;
  60595. }
  60596. var s = this._stride;
  60597. // 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
  60598. var lastFree = new DynamicFloatArrayElementInfo();
  60599. lastFree.offset = this.totalElementCount * s;
  60600. this._freeEntries.push(lastFree);
  60601. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  60602. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  60603. var firstFreeSlotOffset = sortedFree[0].offset;
  60604. var freeZoneSize = 1;
  60605. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  60606. var prevOffset = sortedFree[0].offset;
  60607. for (var i = 1; i < sortedFree.length; i++) {
  60608. // 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
  60609. if (firstFreeSlotOffset >= occupiedZoneSize) {
  60610. break;
  60611. }
  60612. var curFree = sortedFree[i];
  60613. var curOffset = curFree.offset;
  60614. // Compute the distance between this offset and the previous
  60615. var distance = curOffset - prevOffset;
  60616. // If the distance is the stride size, they are adjacent, it good, move to the next
  60617. if (distance === s) {
  60618. // Free zone is one element bigger
  60619. ++freeZoneSize;
  60620. // as we're about to iterate to the next, the cur becomes the previous...
  60621. prevOffset = curOffset;
  60622. continue;
  60623. }
  60624. // Distance is bigger, which means there's x element between the previous free and this one
  60625. var usedRange = (distance / s) - 1;
  60626. // Two cases the free zone is smaller than the data to move or bigger
  60627. // Copy what can fit in the free zone
  60628. var curMoveOffset = curOffset - s;
  60629. var copyCount = Math.min(freeZoneSize, usedRange);
  60630. for (var j = 0; j < copyCount; j++) {
  60631. var freeI = firstFreeSlotOffset / s;
  60632. var curI = curMoveOffset / s;
  60633. var moveEl = sortedAll[curI];
  60634. this._moveElement(moveEl, firstFreeSlotOffset);
  60635. var replacedEl = sortedAll[freeI];
  60636. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  60637. replacedEl.offset = curMoveOffset;
  60638. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  60639. sortedAll[freeI] = moveEl;
  60640. sortedAll[curI] = replacedEl;
  60641. curMoveOffset -= s;
  60642. firstFreeSlotOffset += s;
  60643. }
  60644. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  60645. if (freeZoneSize <= usedRange) {
  60646. firstFreeSlotOffset = curMoveOffset + s;
  60647. freeZoneSize = 1 + copyCount;
  60648. }
  60649. else {
  60650. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  60651. }
  60652. // as we're about to iterate to the next, the cur becomes the previous...
  60653. prevOffset = curOffset;
  60654. }
  60655. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  60656. this._lastUsed = firstFreeSlotOffset - s;
  60657. this._firstFree = firstFreeSlotOffset;
  60658. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  60659. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  60660. this._allEntries = sortedAll;
  60661. return elementsBuffer;
  60662. };
  60663. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  60664. for (var i = 0; i < this._stride; i++) {
  60665. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  60666. }
  60667. element.offset = destOffset;
  60668. };
  60669. DynamicFloatArray.prototype._growBuffer = function () {
  60670. // Allocate the new buffer with 50% more entries, copy the content of the current one
  60671. var newElCount = Math.floor(this.totalElementCount * 1.5);
  60672. var newBuffer = new Float32Array(newElCount * this._stride);
  60673. newBuffer.set(this.buffer);
  60674. var curCount = this.totalElementCount;
  60675. var addedCount = newElCount - this.totalElementCount;
  60676. for (var i = 0; i < addedCount; i++) {
  60677. var element = new DynamicFloatArrayElementInfo();
  60678. element.offset = (curCount + i) * this.stride;
  60679. this._allEntries.push(element);
  60680. this._freeEntries[addedCount - i - 1] = element;
  60681. }
  60682. this._firstFree = curCount * this.stride;
  60683. this.buffer = newBuffer;
  60684. };
  60685. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  60686. /**
  60687. * Get the total count of entries that can fit in the current buffer
  60688. * @returns the elements count
  60689. */
  60690. get: function () {
  60691. return this._allEntries.length;
  60692. },
  60693. enumerable: true,
  60694. configurable: true
  60695. });
  60696. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  60697. /**
  60698. * Get the count of free entries that can still be allocated without resizing the buffer
  60699. * @returns the free elements count
  60700. */
  60701. get: function () {
  60702. return this._freeEntries.length;
  60703. },
  60704. enumerable: true,
  60705. configurable: true
  60706. });
  60707. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  60708. /**
  60709. * Get the count of allocated elements
  60710. * @returns the allocated elements count
  60711. */
  60712. get: function () {
  60713. return this._allEntries.length - this._freeEntries.length;
  60714. },
  60715. enumerable: true,
  60716. configurable: true
  60717. });
  60718. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  60719. /**
  60720. * Return the size of one element in float
  60721. * @returns the size in float
  60722. */
  60723. get: function () {
  60724. return this._stride;
  60725. },
  60726. enumerable: true,
  60727. configurable: true
  60728. });
  60729. DynamicFloatArray.prototype.sort = function () {
  60730. var _this = this;
  60731. if (!this.compareValueOffset) {
  60732. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  60733. }
  60734. var count = this.usedElementCount;
  60735. // Do we have to (re)create the sort table?
  60736. if (!this._sortTable || this._sortTable.length < count) {
  60737. // 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...
  60738. var newCount = Math.min(this.totalElementCount, count * 2);
  60739. this._sortTable = new Array(newCount);
  60740. }
  60741. if (!this._sortedTable || this._sortedTable.length !== count) {
  60742. this._sortedTable = new Array(count);
  60743. }
  60744. // Because, you know...
  60745. this.pack();
  60746. //let stride = this.stride;
  60747. //for (let i = 0; i < count; i++) {
  60748. // let si = this._sortTable[i];
  60749. // if (!si) {
  60750. // si = new SortInfo();
  60751. // this._sortTable[i] = si;
  60752. // }
  60753. // si.entry = this._allEntries[i];
  60754. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  60755. // si.swapedOffset = null;
  60756. // this._sortedTable[i] = si;
  60757. //}
  60758. var curOffset = 0;
  60759. var stride = this.stride;
  60760. for (var i = 0; i < count; i++, curOffset += stride) {
  60761. var si = this._sortTable[i];
  60762. if (!si) {
  60763. si = new SortInfo();
  60764. this._sortTable[i] = si;
  60765. }
  60766. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  60767. si.offset = curOffset;
  60768. si.swapedOffset = null;
  60769. this._sortedTable[i] = si;
  60770. }
  60771. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  60772. if (this.sortingAscending) {
  60773. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  60774. }
  60775. else {
  60776. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  60777. }
  60778. var swapElements = function (src, dst) {
  60779. for (var i = 0; i < stride; i++) {
  60780. var tps = _this.buffer[dst + i];
  60781. _this.buffer[dst + i] = _this.buffer[src + i];
  60782. _this.buffer[src + i] = tps;
  60783. }
  60784. };
  60785. // 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:
  60786. // 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),
  60787. // and I still want something with a good algorithm complexity.
  60788. // 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,
  60789. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  60790. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  60791. // 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
  60792. // until we find a SortInfo object without a swapedOffset which means we got the right location
  60793. // 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
  60794. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  60795. for (var i = 0; i < count; i++) {
  60796. // Get the element to move
  60797. var sourceSI = this._sortedTable[i];
  60798. var destSI = this._sortTable[i];
  60799. var sourceOff = sourceSI.offset;
  60800. // If the source changed location, find the new one
  60801. if (sourceSI.swapedOffset) {
  60802. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  60803. var curSI = sourceSI;
  60804. while (curSI.swapedOffset) {
  60805. curSI = this._sortTable[curSI.swapedOffset / stride];
  60806. }
  60807. // Finally get the right location
  60808. sourceOff = curSI.offset;
  60809. }
  60810. // Tag the element being replaced with its new location
  60811. destSI.swapedOffset = sourceOff;
  60812. // Swap elements (only if needed)
  60813. if (sourceOff !== destSI.offset) {
  60814. swapElements(sourceOff, destSI.offset);
  60815. }
  60816. // Update the offset in the corresponding DFAE
  60817. //sourceSI.entry.offset = destSI.entry.offset;
  60818. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  60819. }
  60820. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  60821. return true;
  60822. };
  60823. return DynamicFloatArray;
  60824. }());
  60825. BABYLON.DynamicFloatArray = DynamicFloatArray;
  60826. var SortInfo = (function () {
  60827. function SortInfo() {
  60828. this.compareData = this.offset = this.swapedOffset = null;
  60829. }
  60830. return SortInfo;
  60831. }());
  60832. })(BABYLON || (BABYLON = {}));
  60833. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  60834. var BABYLON;
  60835. (function (BABYLON) {
  60836. var Debug;
  60837. (function (Debug) {
  60838. /**
  60839. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  60840. */
  60841. var SkeletonViewer = (function () {
  60842. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  60843. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60844. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60845. this.skeleton = skeleton;
  60846. this.mesh = mesh;
  60847. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60848. this.renderingGroupId = renderingGroupId;
  60849. this.color = BABYLON.Color3.White();
  60850. this._debugLines = [];
  60851. this._isEnabled = false;
  60852. this._scene = scene;
  60853. this.update();
  60854. this._renderFunction = this.update.bind(this);
  60855. }
  60856. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60857. get: function () {
  60858. return this._isEnabled;
  60859. },
  60860. set: function (value) {
  60861. if (this._isEnabled === value) {
  60862. return;
  60863. }
  60864. this._isEnabled = value;
  60865. if (value) {
  60866. this._scene.registerBeforeRender(this._renderFunction);
  60867. }
  60868. else {
  60869. this._scene.unregisterBeforeRender(this._renderFunction);
  60870. }
  60871. },
  60872. enumerable: true,
  60873. configurable: true
  60874. });
  60875. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60876. if (x === void 0) { x = 0; }
  60877. if (y === void 0) { y = 0; }
  60878. if (z === void 0) { z = 0; }
  60879. var tmat = BABYLON.Tmp.Matrix[0];
  60880. var parentBone = bone.getParent();
  60881. tmat.copyFrom(bone.getLocalMatrix());
  60882. if (x !== 0 || y !== 0 || z !== 0) {
  60883. var tmat2 = BABYLON.Tmp.Matrix[1];
  60884. BABYLON.Matrix.IdentityToRef(tmat2);
  60885. tmat2.m[12] = x;
  60886. tmat2.m[13] = y;
  60887. tmat2.m[14] = z;
  60888. tmat2.multiplyToRef(tmat, tmat);
  60889. }
  60890. if (parentBone) {
  60891. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60892. }
  60893. tmat.multiplyToRef(meshMat, tmat);
  60894. position.x = tmat.m[12];
  60895. position.y = tmat.m[13];
  60896. position.z = tmat.m[14];
  60897. };
  60898. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60899. var len = bones.length;
  60900. var meshPos = this.mesh.position;
  60901. for (var i = 0; i < len; i++) {
  60902. var bone = bones[i];
  60903. var points = this._debugLines[i];
  60904. if (!points) {
  60905. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60906. this._debugLines[i] = points;
  60907. }
  60908. this._getBonePosition(points[0], bone, meshMat);
  60909. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60910. points[0].subtractInPlace(meshPos);
  60911. points[1].subtractInPlace(meshPos);
  60912. }
  60913. };
  60914. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60915. var len = bones.length;
  60916. var boneNum = 0;
  60917. var meshPos = this.mesh.position;
  60918. for (var i = len - 1; i >= 0; i--) {
  60919. var childBone = bones[i];
  60920. var parentBone = childBone.getParent();
  60921. if (!parentBone) {
  60922. continue;
  60923. }
  60924. var points = this._debugLines[boneNum];
  60925. if (!points) {
  60926. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60927. this._debugLines[boneNum] = points;
  60928. }
  60929. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  60930. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  60931. points[0].subtractInPlace(meshPos);
  60932. points[1].subtractInPlace(meshPos);
  60933. boneNum++;
  60934. }
  60935. };
  60936. SkeletonViewer.prototype.update = function () {
  60937. if (this.autoUpdateBonesMatrices) {
  60938. this.skeleton.computeAbsoluteTransforms();
  60939. }
  60940. if (this.skeleton.bones[0].length === undefined) {
  60941. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60942. }
  60943. else {
  60944. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60945. }
  60946. if (!this._debugMesh) {
  60947. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  60948. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60949. }
  60950. else {
  60951. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60952. }
  60953. this._debugMesh.position.copyFrom(this.mesh.position);
  60954. this._debugMesh.color = this.color;
  60955. };
  60956. SkeletonViewer.prototype.dispose = function () {
  60957. if (this._debugMesh) {
  60958. this.isEnabled = false;
  60959. this._debugMesh.dispose();
  60960. this._debugMesh = null;
  60961. }
  60962. };
  60963. return SkeletonViewer;
  60964. }());
  60965. Debug.SkeletonViewer = SkeletonViewer;
  60966. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60967. })(BABYLON || (BABYLON = {}));
  60968. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60969. var BABYLON;
  60970. (function (BABYLON) {
  60971. var Debug;
  60972. (function (Debug) {
  60973. var AxesViewer = (function () {
  60974. function AxesViewer(scene, scaleLines) {
  60975. if (scaleLines === void 0) { scaleLines = 1; }
  60976. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60977. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60978. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60979. this.scaleLines = 1;
  60980. this.scaleLines = scaleLines;
  60981. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60982. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60983. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60984. this._xmesh.renderingGroupId = 2;
  60985. this._ymesh.renderingGroupId = 2;
  60986. this._zmesh.renderingGroupId = 2;
  60987. this._xmesh.material.checkReadyOnlyOnce = true;
  60988. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60989. this._ymesh.material.checkReadyOnlyOnce = true;
  60990. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60991. this._zmesh.material.checkReadyOnlyOnce = true;
  60992. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60993. this.scene = scene;
  60994. }
  60995. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60996. var scaleLines = this.scaleLines;
  60997. this._xmesh.position.copyFrom(position);
  60998. this._ymesh.position.copyFrom(position);
  60999. this._zmesh.position.copyFrom(position);
  61000. var point2 = this._xline[1];
  61001. point2.x = xaxis.x * scaleLines;
  61002. point2.y = xaxis.y * scaleLines;
  61003. point2.z = xaxis.z * scaleLines;
  61004. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  61005. point2 = this._yline[1];
  61006. point2.x = yaxis.x * scaleLines;
  61007. point2.y = yaxis.y * scaleLines;
  61008. point2.z = yaxis.z * scaleLines;
  61009. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  61010. point2 = this._zline[1];
  61011. point2.x = zaxis.x * scaleLines;
  61012. point2.y = zaxis.y * scaleLines;
  61013. point2.z = zaxis.z * scaleLines;
  61014. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  61015. };
  61016. AxesViewer.prototype.dispose = function () {
  61017. if (this._xmesh) {
  61018. this._xmesh.dispose();
  61019. this._ymesh.dispose();
  61020. this._zmesh.dispose();
  61021. this._xmesh = null;
  61022. this._ymesh = null;
  61023. this._zmesh = null;
  61024. this._xline = null;
  61025. this._yline = null;
  61026. this._zline = null;
  61027. this.scene = null;
  61028. }
  61029. };
  61030. return AxesViewer;
  61031. }());
  61032. Debug.AxesViewer = AxesViewer;
  61033. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61034. })(BABYLON || (BABYLON = {}));
  61035. //# sourceMappingURL=babylon.axesViewer.js.map
  61036. var BABYLON;
  61037. (function (BABYLON) {
  61038. var Debug;
  61039. (function (Debug) {
  61040. var BoneAxesViewer = (function (_super) {
  61041. __extends(BoneAxesViewer, _super);
  61042. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  61043. if (scaleLines === void 0) { scaleLines = 1; }
  61044. var _this = _super.call(this, scene, scaleLines) || this;
  61045. _this.pos = BABYLON.Vector3.Zero();
  61046. _this.xaxis = BABYLON.Vector3.Zero();
  61047. _this.yaxis = BABYLON.Vector3.Zero();
  61048. _this.zaxis = BABYLON.Vector3.Zero();
  61049. _this.mesh = mesh;
  61050. _this.bone = bone;
  61051. return _this;
  61052. }
  61053. BoneAxesViewer.prototype.update = function () {
  61054. var bone = this.bone;
  61055. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  61056. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  61057. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  61058. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  61059. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  61060. };
  61061. BoneAxesViewer.prototype.dispose = function () {
  61062. if (this.pos) {
  61063. this.pos = null;
  61064. this.xaxis = null;
  61065. this.yaxis = null;
  61066. this.zaxis = null;
  61067. this.mesh = null;
  61068. this.bone = null;
  61069. _super.prototype.dispose.call(this);
  61070. }
  61071. };
  61072. return BoneAxesViewer;
  61073. }(Debug.AxesViewer));
  61074. Debug.BoneAxesViewer = BoneAxesViewer;
  61075. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61076. })(BABYLON || (BABYLON = {}));
  61077. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  61078. var BABYLON;
  61079. (function (BABYLON) {
  61080. var RayHelper = (function () {
  61081. function RayHelper(ray) {
  61082. this.ray = ray;
  61083. }
  61084. RayHelper.CreateAndShow = function (ray, scene, color) {
  61085. var helper = new RayHelper(ray);
  61086. helper.show(scene, color);
  61087. return helper;
  61088. };
  61089. RayHelper.prototype.show = function (scene, color) {
  61090. if (!this._renderFunction) {
  61091. var ray = this.ray;
  61092. this._renderFunction = this._render.bind(this);
  61093. this._scene = scene;
  61094. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  61095. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  61096. this._scene.registerBeforeRender(this._renderFunction);
  61097. }
  61098. if (color) {
  61099. this._renderLine.color.copyFrom(color);
  61100. }
  61101. };
  61102. RayHelper.prototype.hide = function () {
  61103. if (this._renderFunction) {
  61104. this._scene.unregisterBeforeRender(this._renderFunction);
  61105. this._scene = null;
  61106. this._renderFunction = null;
  61107. this._renderLine.dispose();
  61108. this._renderLine = null;
  61109. this._renderPoints = null;
  61110. }
  61111. };
  61112. RayHelper.prototype._render = function () {
  61113. var ray = this.ray;
  61114. var point = this._renderPoints[1];
  61115. var len = Math.min(ray.length, 1000000);
  61116. point.copyFrom(ray.direction);
  61117. point.scaleInPlace(len);
  61118. point.addInPlace(ray.origin);
  61119. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  61120. };
  61121. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  61122. this._attachedToMesh = mesh;
  61123. var ray = this.ray;
  61124. if (!ray.direction) {
  61125. ray.direction = BABYLON.Vector3.Zero();
  61126. }
  61127. if (!ray.origin) {
  61128. ray.origin = BABYLON.Vector3.Zero();
  61129. }
  61130. if (length) {
  61131. ray.length = length;
  61132. }
  61133. if (!meshSpaceOrigin) {
  61134. meshSpaceOrigin = BABYLON.Vector3.Zero();
  61135. }
  61136. if (!meshSpaceDirection) {
  61137. // -1 so that this will work with Mesh.lookAt
  61138. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  61139. }
  61140. if (!this._meshSpaceDirection) {
  61141. this._meshSpaceDirection = meshSpaceDirection.clone();
  61142. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  61143. }
  61144. else {
  61145. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  61146. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  61147. }
  61148. if (!this._updateToMeshFunction) {
  61149. this._updateToMeshFunction = this._updateToMesh.bind(this);
  61150. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  61151. }
  61152. this._updateToMesh();
  61153. };
  61154. RayHelper.prototype.detachFromMesh = function () {
  61155. if (this._attachedToMesh) {
  61156. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  61157. this._attachedToMesh = null;
  61158. this._updateToMeshFunction = null;
  61159. }
  61160. };
  61161. RayHelper.prototype._updateToMesh = function () {
  61162. var ray = this.ray;
  61163. if (this._attachedToMesh._isDisposed) {
  61164. this.detachFromMesh();
  61165. return;
  61166. }
  61167. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  61168. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  61169. };
  61170. RayHelper.prototype.dispose = function () {
  61171. this.hide();
  61172. this.detachFromMesh();
  61173. this.ray = null;
  61174. };
  61175. return RayHelper;
  61176. }());
  61177. BABYLON.RayHelper = RayHelper;
  61178. })(BABYLON || (BABYLON = {}));
  61179. //# sourceMappingURL=babylon.rayHelper.js.map
  61180. var BABYLON;
  61181. (function (BABYLON) {
  61182. var DebugLayer = (function () {
  61183. function DebugLayer(scene) {
  61184. this._scene = scene;
  61185. }
  61186. /** Creates the inspector window. */
  61187. DebugLayer.prototype._createInspector = function (config) {
  61188. if (config === void 0) { config = {}; }
  61189. var popup = config.popup || false;
  61190. var initialTab = config.initialTab || 0;
  61191. var parentElement = config.parentElement || null;
  61192. if (!this._inspector) {
  61193. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  61194. } // else nothing to do,; instance is already existing
  61195. };
  61196. DebugLayer.prototype.isVisible = function () {
  61197. if (!this._inspector) {
  61198. return false;
  61199. }
  61200. return true;
  61201. };
  61202. DebugLayer.prototype.hide = function () {
  61203. if (this._inspector) {
  61204. try {
  61205. this._inspector.dispose();
  61206. }
  61207. catch (e) {
  61208. // If the inspector has been removed directly from the inspector tool
  61209. }
  61210. this._inspector = null;
  61211. }
  61212. };
  61213. DebugLayer.prototype.show = function (config) {
  61214. if (config === void 0) { config = {}; }
  61215. if (typeof INSPECTOR == 'undefined') {
  61216. // Load inspector and add it to the DOM
  61217. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  61218. }
  61219. else {
  61220. // Otherwise creates the inspector
  61221. this._createInspector(config);
  61222. }
  61223. };
  61224. return DebugLayer;
  61225. }());
  61226. // Get protocol used - http or https
  61227. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  61228. BABYLON.DebugLayer = DebugLayer;
  61229. })(BABYLON || (BABYLON = {}));
  61230. //# sourceMappingURL=babylon.debugLayer.js.map
  61231. var BABYLON;
  61232. (function (BABYLON) {
  61233. var Debug;
  61234. (function (Debug) {
  61235. var PhysicsViewer = (function () {
  61236. function PhysicsViewer(scene) {
  61237. this._impostors = [];
  61238. this._meshes = [];
  61239. this._numMeshes = 0;
  61240. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61241. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  61242. }
  61243. PhysicsViewer.prototype._updateDebugMeshes = function () {
  61244. var plugin = this._physicsEnginePlugin;
  61245. for (var i = 0; i < this._numMeshes; i++) {
  61246. if (this._impostors[i].isDisposed) {
  61247. this.hideImpostor(this._impostors[i--]);
  61248. }
  61249. else {
  61250. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  61251. }
  61252. }
  61253. };
  61254. PhysicsViewer.prototype.showImpostor = function (impostor) {
  61255. for (var i = 0; i < this._numMeshes; i++) {
  61256. if (this._impostors[i] == impostor) {
  61257. return;
  61258. }
  61259. }
  61260. var debugMesh = this._physicsEnginePlugin.getDebugMesh(impostor, this._scene);
  61261. if (debugMesh) {
  61262. this._impostors[this._numMeshes] = impostor;
  61263. this._meshes[this._numMeshes] = debugMesh;
  61264. if (this._numMeshes === 0) {
  61265. this._renderFunction = this._updateDebugMeshes.bind(this);
  61266. this._scene.registerBeforeRender(this._renderFunction);
  61267. }
  61268. this._numMeshes++;
  61269. }
  61270. };
  61271. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  61272. var removed = false;
  61273. for (var i = 0; i < this._numMeshes; i++) {
  61274. if (this._impostors[i] == impostor) {
  61275. this._scene.removeMesh(this._meshes[i]);
  61276. this._meshes[i].dispose();
  61277. this._numMeshes--;
  61278. if (this._numMeshes > 0) {
  61279. this._meshes[i] = this._meshes[this._numMeshes];
  61280. this._impostors[i] = this._impostors[this._numMeshes];
  61281. this._meshes[this._numMeshes] = null;
  61282. this._impostors[this._numMeshes] = null;
  61283. }
  61284. else {
  61285. this._meshes[0] = null;
  61286. this._impostors[0] = null;
  61287. }
  61288. removed = true;
  61289. break;
  61290. }
  61291. }
  61292. if (removed && this._numMeshes === 0) {
  61293. this._scene.unregisterBeforeRender(this._renderFunction);
  61294. }
  61295. };
  61296. PhysicsViewer.prototype.dispose = function () {
  61297. for (var i = 0; i < this._numMeshes; i++) {
  61298. this.hideImpostor(this._impostors[i]);
  61299. }
  61300. this._impostors.length = 0;
  61301. this._scene = null;
  61302. this._physicsEnginePlugin = null;
  61303. };
  61304. return PhysicsViewer;
  61305. }());
  61306. Debug.PhysicsViewer = PhysicsViewer;
  61307. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61308. })(BABYLON || (BABYLON = {}));
  61309. //# sourceMappingURL=babylon.physicsViewer.js.map
  61310. var BABYLON;
  61311. (function (BABYLON) {
  61312. var BoundingBoxRenderer = (function () {
  61313. function BoundingBoxRenderer(scene) {
  61314. this.frontColor = new BABYLON.Color3(1, 1, 1);
  61315. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  61316. this.showBackLines = true;
  61317. this.renderList = new BABYLON.SmartArray(32);
  61318. this._vertexBuffers = {};
  61319. this._scene = scene;
  61320. }
  61321. BoundingBoxRenderer.prototype._prepareRessources = function () {
  61322. if (this._colorShader) {
  61323. return;
  61324. }
  61325. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  61326. attributes: [BABYLON.VertexBuffer.PositionKind],
  61327. uniforms: ["world", "viewProjection", "color"]
  61328. });
  61329. var engine = this._scene.getEngine();
  61330. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  61331. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  61332. 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]);
  61333. };
  61334. BoundingBoxRenderer.prototype.reset = function () {
  61335. this.renderList.reset();
  61336. };
  61337. BoundingBoxRenderer.prototype.render = function () {
  61338. if (this.renderList.length === 0) {
  61339. return;
  61340. }
  61341. this._prepareRessources();
  61342. if (!this._colorShader.isReady()) {
  61343. return;
  61344. }
  61345. var engine = this._scene.getEngine();
  61346. engine.setDepthWrite(false);
  61347. this._colorShader._preBind();
  61348. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  61349. var boundingBox = this.renderList.data[boundingBoxIndex];
  61350. var min = boundingBox.minimum;
  61351. var max = boundingBox.maximum;
  61352. var diff = max.subtract(min);
  61353. var median = min.add(diff.scale(0.5));
  61354. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61355. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61356. .multiply(boundingBox.getWorldMatrix());
  61357. // VBOs
  61358. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61359. if (this.showBackLines) {
  61360. // Back
  61361. engine.setDepthFunctionToGreaterOrEqual();
  61362. this._scene.resetCachedMaterial();
  61363. this._colorShader.setColor4("color", this.backColor.toColor4());
  61364. this._colorShader.bind(worldMatrix);
  61365. // Draw order
  61366. engine.draw(false, 0, 24);
  61367. }
  61368. // Front
  61369. engine.setDepthFunctionToLess();
  61370. this._scene.resetCachedMaterial();
  61371. this._colorShader.setColor4("color", this.frontColor.toColor4());
  61372. this._colorShader.bind(worldMatrix);
  61373. // Draw order
  61374. engine.draw(false, 0, 24);
  61375. }
  61376. this._colorShader.unbind();
  61377. engine.setDepthFunctionToLessOrEqual();
  61378. engine.setDepthWrite(true);
  61379. };
  61380. BoundingBoxRenderer.prototype.dispose = function () {
  61381. if (!this._colorShader) {
  61382. return;
  61383. }
  61384. this.renderList.dispose();
  61385. this._colorShader.dispose();
  61386. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61387. if (buffer) {
  61388. buffer.dispose();
  61389. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61390. }
  61391. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61392. };
  61393. return BoundingBoxRenderer;
  61394. }());
  61395. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  61396. })(BABYLON || (BABYLON = {}));
  61397. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  61398. var BABYLON;
  61399. (function (BABYLON) {
  61400. var MorphTarget = (function () {
  61401. function MorphTarget(name, influence) {
  61402. if (influence === void 0) { influence = 0; }
  61403. this.name = name;
  61404. this.animations = new Array();
  61405. this.onInfluenceChanged = new BABYLON.Observable();
  61406. this.influence = influence;
  61407. }
  61408. Object.defineProperty(MorphTarget.prototype, "influence", {
  61409. get: function () {
  61410. return this._influence;
  61411. },
  61412. set: function (influence) {
  61413. if (this._influence === influence) {
  61414. return;
  61415. }
  61416. var previous = this._influence;
  61417. this._influence = influence;
  61418. if (this.onInfluenceChanged.hasObservers) {
  61419. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  61420. }
  61421. },
  61422. enumerable: true,
  61423. configurable: true
  61424. });
  61425. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  61426. get: function () {
  61427. return this._normals !== undefined;
  61428. },
  61429. enumerable: true,
  61430. configurable: true
  61431. });
  61432. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  61433. get: function () {
  61434. return this._tangents !== undefined;
  61435. },
  61436. enumerable: true,
  61437. configurable: true
  61438. });
  61439. MorphTarget.prototype.setPositions = function (data) {
  61440. this._positions = new Float32Array(data);
  61441. };
  61442. MorphTarget.prototype.getPositions = function () {
  61443. return this._positions;
  61444. };
  61445. MorphTarget.prototype.setNormals = function (data) {
  61446. this._normals = new Float32Array(data);
  61447. };
  61448. MorphTarget.prototype.getNormals = function () {
  61449. return this._normals;
  61450. };
  61451. MorphTarget.prototype.setTangents = function (data) {
  61452. this._tangents = new Float32Array(data);
  61453. };
  61454. MorphTarget.prototype.getTangents = function () {
  61455. return this._tangents;
  61456. };
  61457. /**
  61458. * Serializes the current target into a Serialization object.
  61459. * Returns the serialized object.
  61460. */
  61461. MorphTarget.prototype.serialize = function () {
  61462. var serializationObject = {};
  61463. serializationObject.name = this.name;
  61464. serializationObject.influence = this.influence;
  61465. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  61466. if (this.hasNormals) {
  61467. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  61468. }
  61469. if (this.hasTangents) {
  61470. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  61471. }
  61472. return serializationObject;
  61473. };
  61474. // Statics
  61475. MorphTarget.Parse = function (serializationObject) {
  61476. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  61477. result.setPositions(serializationObject.positions);
  61478. if (serializationObject.normals) {
  61479. result.setNormals(serializationObject.normals);
  61480. }
  61481. if (serializationObject.tangents) {
  61482. result.setTangents(serializationObject.tangents);
  61483. }
  61484. return result;
  61485. };
  61486. MorphTarget.FromMesh = function (mesh, name, influence) {
  61487. if (!name) {
  61488. name = mesh.name;
  61489. }
  61490. var result = new MorphTarget(name, influence);
  61491. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  61492. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61493. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  61494. }
  61495. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  61496. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  61497. }
  61498. return result;
  61499. };
  61500. return MorphTarget;
  61501. }());
  61502. BABYLON.MorphTarget = MorphTarget;
  61503. })(BABYLON || (BABYLON = {}));
  61504. //# sourceMappingURL=babylon.morphTarget.js.map
  61505. var BABYLON;
  61506. (function (BABYLON) {
  61507. var MorphTargetManager = (function () {
  61508. function MorphTargetManager(scene) {
  61509. this._targets = new Array();
  61510. this._targetObservable = new Array();
  61511. this._activeTargets = new BABYLON.SmartArray(16);
  61512. this._supportsNormals = false;
  61513. this._supportsTangents = false;
  61514. this._vertexCount = 0;
  61515. this._uniqueId = 0;
  61516. if (!scene) {
  61517. scene = BABYLON.Engine.LastCreatedScene;
  61518. }
  61519. this._scene = scene;
  61520. this._scene.morphTargetManagers.push(this);
  61521. this._uniqueId = scene.getUniqueId();
  61522. }
  61523. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  61524. get: function () {
  61525. return this._uniqueId;
  61526. },
  61527. enumerable: true,
  61528. configurable: true
  61529. });
  61530. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  61531. get: function () {
  61532. return this._vertexCount;
  61533. },
  61534. enumerable: true,
  61535. configurable: true
  61536. });
  61537. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  61538. get: function () {
  61539. return this._supportsNormals;
  61540. },
  61541. enumerable: true,
  61542. configurable: true
  61543. });
  61544. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  61545. get: function () {
  61546. return this._supportsTangents;
  61547. },
  61548. enumerable: true,
  61549. configurable: true
  61550. });
  61551. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  61552. get: function () {
  61553. return this._targets.length;
  61554. },
  61555. enumerable: true,
  61556. configurable: true
  61557. });
  61558. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  61559. get: function () {
  61560. return this._activeTargets.length;
  61561. },
  61562. enumerable: true,
  61563. configurable: true
  61564. });
  61565. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  61566. get: function () {
  61567. return this._influences;
  61568. },
  61569. enumerable: true,
  61570. configurable: true
  61571. });
  61572. MorphTargetManager.prototype.getActiveTarget = function (index) {
  61573. return this._activeTargets.data[index];
  61574. };
  61575. MorphTargetManager.prototype.getTarget = function (index) {
  61576. return this._targets[index];
  61577. };
  61578. MorphTargetManager.prototype.addTarget = function (target) {
  61579. var _this = this;
  61580. if (this._vertexCount) {
  61581. if (this._vertexCount !== target.getPositions().length / 3) {
  61582. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  61583. return;
  61584. }
  61585. }
  61586. this._targets.push(target);
  61587. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  61588. _this._syncActiveTargets(needUpdate);
  61589. }));
  61590. this._syncActiveTargets(true);
  61591. };
  61592. MorphTargetManager.prototype.removeTarget = function (target) {
  61593. var index = this._targets.indexOf(target);
  61594. if (index >= 0) {
  61595. this._targets.splice(index, 1);
  61596. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  61597. this._vertexCount = 0;
  61598. this._syncActiveTargets(true);
  61599. }
  61600. };
  61601. /**
  61602. * Serializes the current manager into a Serialization object.
  61603. * Returns the serialized object.
  61604. */
  61605. MorphTargetManager.prototype.serialize = function () {
  61606. var serializationObject = {};
  61607. serializationObject.id = this.uniqueId;
  61608. serializationObject.targets = [];
  61609. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  61610. var target = _a[_i];
  61611. serializationObject.targets.push(target.serialize());
  61612. }
  61613. return serializationObject;
  61614. };
  61615. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  61616. this._syncActiveTargets(needUpdate);
  61617. };
  61618. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  61619. this._activeTargets.reset();
  61620. var tempInfluences = [];
  61621. this._supportsNormals = true;
  61622. this._supportsTangents = true;
  61623. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  61624. var target = _a[_i];
  61625. if (target.influence > 0) {
  61626. this._activeTargets.push(target);
  61627. tempInfluences.push(target.influence);
  61628. this._supportsNormals = this._supportsNormals && target.hasNormals;
  61629. this._supportsTangents = this._supportsTangents && target.hasTangents;
  61630. if (this._vertexCount === 0) {
  61631. this._vertexCount = target.getPositions().length / 3;
  61632. }
  61633. }
  61634. }
  61635. this._influences = new Float32Array(tempInfluences);
  61636. if (needUpdate) {
  61637. // Flag meshes as dirty to resync with the active targets
  61638. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  61639. var mesh = _c[_b];
  61640. if (mesh.morphTargetManager === this) {
  61641. mesh._syncGeometryWithMorphTargetManager();
  61642. }
  61643. }
  61644. }
  61645. };
  61646. // Statics
  61647. MorphTargetManager.Parse = function (serializationObject, scene) {
  61648. var result = new MorphTargetManager(scene);
  61649. result._uniqueId = serializationObject.id;
  61650. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  61651. var targetData = _a[_i];
  61652. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  61653. }
  61654. return result;
  61655. };
  61656. return MorphTargetManager;
  61657. }());
  61658. BABYLON.MorphTargetManager = MorphTargetManager;
  61659. })(BABYLON || (BABYLON = {}));
  61660. //# sourceMappingURL=babylon.morphTargetManager.js.map
  61661. var BABYLON;
  61662. (function (BABYLON) {
  61663. /**
  61664. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  61665. * It can help converting any input color in a desired output one. This can then be used to create effects
  61666. * from sepia, black and white to sixties or futuristic rendering...
  61667. *
  61668. * The only supported format is currently 3dl.
  61669. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  61670. */
  61671. var ColorGradingTexture = (function (_super) {
  61672. __extends(ColorGradingTexture, _super);
  61673. /**
  61674. * Instantiates a ColorGradingTexture from the following parameters.
  61675. *
  61676. * @param url The location of the color gradind data (currently only supporting 3dl)
  61677. * @param scene The scene the texture will be used in
  61678. */
  61679. function ColorGradingTexture(url, scene) {
  61680. var _this = _super.call(this, scene) || this;
  61681. if (!url) {
  61682. return _this;
  61683. }
  61684. _this._textureMatrix = BABYLON.Matrix.Identity();
  61685. _this.name = url;
  61686. _this.url = url;
  61687. _this.hasAlpha = false;
  61688. _this.isCube = false;
  61689. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61690. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61691. _this.anisotropicFilteringLevel = 1;
  61692. _this._texture = _this._getFromCache(url, true);
  61693. if (!_this._texture) {
  61694. if (!scene.useDelayedTextureLoading) {
  61695. _this.loadTexture();
  61696. }
  61697. else {
  61698. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  61699. }
  61700. }
  61701. return _this;
  61702. }
  61703. /**
  61704. * Returns the texture matrix used in most of the material.
  61705. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  61706. */
  61707. ColorGradingTexture.prototype.getTextureMatrix = function () {
  61708. return this._textureMatrix;
  61709. };
  61710. /**
  61711. * Occurs when the file being loaded is a .3dl LUT file.
  61712. */
  61713. ColorGradingTexture.prototype.load3dlTexture = function () {
  61714. var _this = this;
  61715. var mipLevels = 0;
  61716. var floatArrayView = null;
  61717. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61718. this._texture = texture;
  61719. var callback = function (text) {
  61720. var data;
  61721. var tempData;
  61722. var line;
  61723. var lines = text.split('\n');
  61724. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  61725. var maxColor = 0;
  61726. for (var i = 0; i < lines.length; i++) {
  61727. line = lines[i];
  61728. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  61729. continue;
  61730. if (line.indexOf('#') === 0)
  61731. continue;
  61732. var words = line.split(" ");
  61733. if (size === 0) {
  61734. // Number of space + one
  61735. size = words.length;
  61736. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  61737. tempData = new Float32Array(size * size * size * 4);
  61738. continue;
  61739. }
  61740. if (size != 0) {
  61741. var r = Math.max(parseInt(words[0]), 0);
  61742. var g = Math.max(parseInt(words[1]), 0);
  61743. var b = Math.max(parseInt(words[2]), 0);
  61744. maxColor = Math.max(r, maxColor);
  61745. maxColor = Math.max(g, maxColor);
  61746. maxColor = Math.max(b, maxColor);
  61747. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  61748. tempData[pixelStorageIndex + 0] = r;
  61749. tempData[pixelStorageIndex + 1] = g;
  61750. tempData[pixelStorageIndex + 2] = b;
  61751. pixelIndexSlice++;
  61752. if (pixelIndexSlice % size == 0) {
  61753. pixelIndexH++;
  61754. pixelIndexSlice = 0;
  61755. if (pixelIndexH % size == 0) {
  61756. pixelIndexW++;
  61757. pixelIndexH = 0;
  61758. }
  61759. }
  61760. }
  61761. }
  61762. for (var i = 0; i < tempData.length; i++) {
  61763. if (i > 0 && (i + 1) % 4 === 0) {
  61764. data[i] = 255;
  61765. }
  61766. else {
  61767. var value = tempData[i];
  61768. data[i] = (value / maxColor * 255);
  61769. }
  61770. }
  61771. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  61772. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  61773. };
  61774. BABYLON.Tools.LoadFile(this.url, callback);
  61775. return this._texture;
  61776. };
  61777. /**
  61778. * Starts the loading process of the texture.
  61779. */
  61780. ColorGradingTexture.prototype.loadTexture = function () {
  61781. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  61782. this.load3dlTexture();
  61783. }
  61784. };
  61785. /**
  61786. * Clones the color gradind texture.
  61787. */
  61788. ColorGradingTexture.prototype.clone = function () {
  61789. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  61790. // Base texture
  61791. newTexture.level = this.level;
  61792. return newTexture;
  61793. };
  61794. /**
  61795. * Called during delayed load for textures.
  61796. */
  61797. ColorGradingTexture.prototype.delayLoad = function () {
  61798. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  61799. return;
  61800. }
  61801. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  61802. this._texture = this._getFromCache(this.url, true);
  61803. if (!this._texture) {
  61804. this.loadTexture();
  61805. }
  61806. };
  61807. /**
  61808. * Parses a color grading texture serialized by Babylon.
  61809. * @param parsedTexture The texture information being parsedTexture
  61810. * @param scene The scene to load the texture in
  61811. * @param rootUrl The root url of the data assets to load
  61812. * @return A color gradind texture
  61813. */
  61814. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  61815. var texture = null;
  61816. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  61817. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  61818. texture.name = parsedTexture.name;
  61819. texture.level = parsedTexture.level;
  61820. }
  61821. return texture;
  61822. };
  61823. /**
  61824. * Serializes the LUT texture to json format.
  61825. */
  61826. ColorGradingTexture.prototype.serialize = function () {
  61827. if (!this.name) {
  61828. return null;
  61829. }
  61830. var serializationObject = {};
  61831. serializationObject.name = this.name;
  61832. serializationObject.level = this.level;
  61833. serializationObject.customType = "BABYLON.ColorGradingTexture";
  61834. return serializationObject;
  61835. };
  61836. return ColorGradingTexture;
  61837. }(BABYLON.BaseTexture));
  61838. /**
  61839. * Empty line regex stored for GC.
  61840. */
  61841. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  61842. BABYLON.ColorGradingTexture = ColorGradingTexture;
  61843. })(BABYLON || (BABYLON = {}));
  61844. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  61845. var BABYLON;
  61846. (function (BABYLON) {
  61847. /**
  61848. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  61849. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  61850. * 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;
  61851. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  61852. */
  61853. var ColorCurves = (function () {
  61854. function ColorCurves() {
  61855. this._dirty = true;
  61856. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  61857. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  61858. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  61859. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  61860. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  61861. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  61862. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  61863. this._globalHue = 30;
  61864. this._globalDensity = 0;
  61865. this._globalSaturation = 0;
  61866. this._globalExposure = 0;
  61867. this._highlightsHue = 30;
  61868. this._highlightsDensity = 0;
  61869. this._highlightsSaturation = 0;
  61870. this._highlightsExposure = 0;
  61871. this._midtonesHue = 30;
  61872. this._midtonesDensity = 0;
  61873. this._midtonesSaturation = 0;
  61874. this._midtonesExposure = 0;
  61875. this._shadowsHue = 30;
  61876. this._shadowsDensity = 0;
  61877. this._shadowsSaturation = 0;
  61878. this._shadowsExposure = 0;
  61879. }
  61880. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  61881. /**
  61882. * Gets the global Hue value.
  61883. * 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).
  61884. */
  61885. get: function () {
  61886. return this._globalHue;
  61887. },
  61888. /**
  61889. * Sets the global Hue value.
  61890. * 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).
  61891. */
  61892. set: function (value) {
  61893. this._globalHue = value;
  61894. this._dirty = true;
  61895. },
  61896. enumerable: true,
  61897. configurable: true
  61898. });
  61899. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  61900. /**
  61901. * Gets the global Density value.
  61902. * 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.
  61903. * Values less than zero provide a filter of opposite hue.
  61904. */
  61905. get: function () {
  61906. return this._globalDensity;
  61907. },
  61908. /**
  61909. * Sets the global Density value.
  61910. * 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.
  61911. * Values less than zero provide a filter of opposite hue.
  61912. */
  61913. set: function (value) {
  61914. this._globalDensity = value;
  61915. this._dirty = true;
  61916. },
  61917. enumerable: true,
  61918. configurable: true
  61919. });
  61920. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  61921. /**
  61922. * Gets the global Saturation value.
  61923. * 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.
  61924. */
  61925. get: function () {
  61926. return this._globalSaturation;
  61927. },
  61928. /**
  61929. * Sets the global Saturation value.
  61930. * 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.
  61931. */
  61932. set: function (value) {
  61933. this._globalSaturation = value;
  61934. this._dirty = true;
  61935. },
  61936. enumerable: true,
  61937. configurable: true
  61938. });
  61939. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  61940. /**
  61941. * Gets the highlights Hue value.
  61942. * 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).
  61943. */
  61944. get: function () {
  61945. return this._highlightsHue;
  61946. },
  61947. /**
  61948. * Sets the highlights Hue value.
  61949. * 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).
  61950. */
  61951. set: function (value) {
  61952. this._highlightsHue = value;
  61953. this._dirty = true;
  61954. },
  61955. enumerable: true,
  61956. configurable: true
  61957. });
  61958. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  61959. /**
  61960. * Gets the highlights Density value.
  61961. * 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.
  61962. * Values less than zero provide a filter of opposite hue.
  61963. */
  61964. get: function () {
  61965. return this._highlightsDensity;
  61966. },
  61967. /**
  61968. * Sets the highlights Density value.
  61969. * 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.
  61970. * Values less than zero provide a filter of opposite hue.
  61971. */
  61972. set: function (value) {
  61973. this._highlightsDensity = value;
  61974. this._dirty = true;
  61975. },
  61976. enumerable: true,
  61977. configurable: true
  61978. });
  61979. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  61980. /**
  61981. * Gets the highlights Saturation value.
  61982. * 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.
  61983. */
  61984. get: function () {
  61985. return this._highlightsSaturation;
  61986. },
  61987. /**
  61988. * Sets the highlights Saturation value.
  61989. * 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.
  61990. */
  61991. set: function (value) {
  61992. this._highlightsSaturation = value;
  61993. this._dirty = true;
  61994. },
  61995. enumerable: true,
  61996. configurable: true
  61997. });
  61998. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  61999. /**
  62000. * Gets the highlights Exposure value.
  62001. * 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.
  62002. */
  62003. get: function () {
  62004. return this._highlightsExposure;
  62005. },
  62006. /**
  62007. * Sets the highlights Exposure value.
  62008. * 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.
  62009. */
  62010. set: function (value) {
  62011. this._highlightsExposure = value;
  62012. this._dirty = true;
  62013. },
  62014. enumerable: true,
  62015. configurable: true
  62016. });
  62017. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  62018. /**
  62019. * Gets the midtones Hue value.
  62020. * 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).
  62021. */
  62022. get: function () {
  62023. return this._midtonesHue;
  62024. },
  62025. /**
  62026. * Sets the midtones Hue value.
  62027. * 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).
  62028. */
  62029. set: function (value) {
  62030. this._midtonesHue = value;
  62031. this._dirty = true;
  62032. },
  62033. enumerable: true,
  62034. configurable: true
  62035. });
  62036. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  62037. /**
  62038. * Gets the midtones Density value.
  62039. * 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.
  62040. * Values less than zero provide a filter of opposite hue.
  62041. */
  62042. get: function () {
  62043. return this._midtonesDensity;
  62044. },
  62045. /**
  62046. * Sets the midtones Density value.
  62047. * 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.
  62048. * Values less than zero provide a filter of opposite hue.
  62049. */
  62050. set: function (value) {
  62051. this._midtonesDensity = value;
  62052. this._dirty = true;
  62053. },
  62054. enumerable: true,
  62055. configurable: true
  62056. });
  62057. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  62058. /**
  62059. * Gets the midtones Saturation value.
  62060. * 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.
  62061. */
  62062. get: function () {
  62063. return this._midtonesSaturation;
  62064. },
  62065. /**
  62066. * Sets the midtones Saturation value.
  62067. * 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.
  62068. */
  62069. set: function (value) {
  62070. this._midtonesSaturation = value;
  62071. this._dirty = true;
  62072. },
  62073. enumerable: true,
  62074. configurable: true
  62075. });
  62076. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  62077. /**
  62078. * Gets the midtones Exposure value.
  62079. * 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.
  62080. */
  62081. get: function () {
  62082. return this._midtonesExposure;
  62083. },
  62084. /**
  62085. * Sets the midtones Exposure value.
  62086. * 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.
  62087. */
  62088. set: function (value) {
  62089. this._midtonesExposure = value;
  62090. this._dirty = true;
  62091. },
  62092. enumerable: true,
  62093. configurable: true
  62094. });
  62095. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  62096. /**
  62097. * Gets the shadows Hue value.
  62098. * 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).
  62099. */
  62100. get: function () {
  62101. return this._shadowsHue;
  62102. },
  62103. /**
  62104. * Sets the shadows Hue value.
  62105. * 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).
  62106. */
  62107. set: function (value) {
  62108. this._shadowsHue = value;
  62109. this._dirty = true;
  62110. },
  62111. enumerable: true,
  62112. configurable: true
  62113. });
  62114. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  62115. /**
  62116. * Gets the shadows Density value.
  62117. * 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.
  62118. * Values less than zero provide a filter of opposite hue.
  62119. */
  62120. get: function () {
  62121. return this._shadowsDensity;
  62122. },
  62123. /**
  62124. * Sets the shadows Density value.
  62125. * 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.
  62126. * Values less than zero provide a filter of opposite hue.
  62127. */
  62128. set: function (value) {
  62129. this._shadowsDensity = value;
  62130. this._dirty = true;
  62131. },
  62132. enumerable: true,
  62133. configurable: true
  62134. });
  62135. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  62136. /**
  62137. * Gets the shadows Saturation value.
  62138. * 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.
  62139. */
  62140. get: function () {
  62141. return this._shadowsSaturation;
  62142. },
  62143. /**
  62144. * Sets the shadows Saturation value.
  62145. * 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.
  62146. */
  62147. set: function (value) {
  62148. this._shadowsSaturation = value;
  62149. this._dirty = true;
  62150. },
  62151. enumerable: true,
  62152. configurable: true
  62153. });
  62154. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  62155. /**
  62156. * Gets the shadows Exposure value.
  62157. * 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.
  62158. */
  62159. get: function () {
  62160. return this._shadowsExposure;
  62161. },
  62162. /**
  62163. * Sets the shadows Exposure value.
  62164. * 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.
  62165. */
  62166. set: function (value) {
  62167. this._shadowsExposure = value;
  62168. this._dirty = true;
  62169. },
  62170. enumerable: true,
  62171. configurable: true
  62172. });
  62173. /**
  62174. * Binds the color curves to the shader.
  62175. * @param colorCurves The color curve to bind
  62176. * @param effect The effect to bind to
  62177. */
  62178. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  62179. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  62180. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  62181. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  62182. if (colorCurves._dirty) {
  62183. colorCurves._dirty = false;
  62184. // Fill in global info.
  62185. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  62186. // Compute highlights info.
  62187. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  62188. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  62189. // Compute midtones info.
  62190. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  62191. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  62192. // Compute shadows info.
  62193. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  62194. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  62195. // Compute deltas (neutral is midtones).
  62196. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  62197. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  62198. }
  62199. if (effect) {
  62200. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  62201. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  62202. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  62203. }
  62204. };
  62205. /**
  62206. * Prepare the list of uniforms associated with the ColorCurves effects.
  62207. * @param uniformsList The list of uniforms used in the effect
  62208. */
  62209. ColorCurves.PrepareUniforms = function (uniformsList) {
  62210. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  62211. };
  62212. /**
  62213. * Returns color grading data based on a hue, density, saturation and exposure value.
  62214. * @param filterHue The hue of the color filter.
  62215. * @param filterDensity The density of the color filter.
  62216. * @param saturation The saturation.
  62217. * @param exposure The exposure.
  62218. * @param result The result data container.
  62219. */
  62220. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  62221. if (hue == null) {
  62222. return;
  62223. }
  62224. hue = ColorCurves.clamp(hue, 0, 360);
  62225. density = ColorCurves.clamp(density, -100, 100);
  62226. saturation = ColorCurves.clamp(saturation, -100, 100);
  62227. exposure = ColorCurves.clamp(exposure, -100, 100);
  62228. // Remap the slider/config filter density with non-linear mapping and also scale by half
  62229. // so that the maximum filter density is only 50% control. This provides fine control
  62230. // for small values and reasonable range.
  62231. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  62232. density *= 0.5;
  62233. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  62234. if (density < 0) {
  62235. density *= -1;
  62236. hue = (hue + 180) % 360;
  62237. }
  62238. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  62239. result.scaleToRef(2, result);
  62240. result.a = 1 + 0.01 * saturation;
  62241. };
  62242. /**
  62243. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  62244. * @param value The input slider value in range [-100,100].
  62245. * @returns Adjusted value.
  62246. */
  62247. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  62248. value /= 100;
  62249. var x = Math.abs(value);
  62250. x = Math.pow(x, 2);
  62251. if (value < 0) {
  62252. x *= -1;
  62253. }
  62254. x *= 100;
  62255. return x;
  62256. };
  62257. /**
  62258. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  62259. * @param hue The hue (H) input.
  62260. * @param saturation The saturation (S) input.
  62261. * @param brightness The brightness (B) input.
  62262. * @result An RGBA color represented as Vector4.
  62263. */
  62264. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  62265. var h = ColorCurves.clamp(hue, 0, 360);
  62266. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  62267. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  62268. if (s === 0) {
  62269. result.r = v;
  62270. result.g = v;
  62271. result.b = v;
  62272. }
  62273. else {
  62274. // sector 0 to 5
  62275. h /= 60;
  62276. var i = Math.floor(h);
  62277. // fractional part of h
  62278. var f = h - i;
  62279. var p = v * (1 - s);
  62280. var q = v * (1 - s * f);
  62281. var t = v * (1 - s * (1 - f));
  62282. switch (i) {
  62283. case 0:
  62284. result.r = v;
  62285. result.g = t;
  62286. result.b = p;
  62287. break;
  62288. case 1:
  62289. result.r = q;
  62290. result.g = v;
  62291. result.b = p;
  62292. break;
  62293. case 2:
  62294. result.r = p;
  62295. result.g = v;
  62296. result.b = t;
  62297. break;
  62298. case 3:
  62299. result.r = p;
  62300. result.g = q;
  62301. result.b = v;
  62302. break;
  62303. case 4:
  62304. result.r = t;
  62305. result.g = p;
  62306. result.b = v;
  62307. break;
  62308. default:
  62309. result.r = v;
  62310. result.g = p;
  62311. result.b = q;
  62312. break;
  62313. }
  62314. }
  62315. result.a = 1;
  62316. };
  62317. /**
  62318. * Returns a value clamped between min and max
  62319. * @param value The value to clamp
  62320. * @param min The minimum of value
  62321. * @param max The maximum of value
  62322. * @returns The clamped value.
  62323. */
  62324. ColorCurves.clamp = function (value, min, max) {
  62325. return Math.min(Math.max(value, min), max);
  62326. };
  62327. /**
  62328. * Clones the current color curve instance.
  62329. * @return The cloned curves
  62330. */
  62331. ColorCurves.prototype.clone = function () {
  62332. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  62333. };
  62334. /**
  62335. * Serializes the current color curve instance to a json representation.
  62336. * @return a JSON representation
  62337. */
  62338. ColorCurves.prototype.serialize = function () {
  62339. return BABYLON.SerializationHelper.Serialize(this);
  62340. };
  62341. /**
  62342. * Parses the color curve from a json representation.
  62343. * @param source the JSON source to parse
  62344. * @return The parsed curves
  62345. */
  62346. ColorCurves.Parse = function (source) {
  62347. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  62348. };
  62349. return ColorCurves;
  62350. }());
  62351. __decorate([
  62352. BABYLON.serialize()
  62353. ], ColorCurves.prototype, "_globalHue", void 0);
  62354. __decorate([
  62355. BABYLON.serialize()
  62356. ], ColorCurves.prototype, "_globalDensity", void 0);
  62357. __decorate([
  62358. BABYLON.serialize()
  62359. ], ColorCurves.prototype, "_globalSaturation", void 0);
  62360. __decorate([
  62361. BABYLON.serialize()
  62362. ], ColorCurves.prototype, "_globalExposure", void 0);
  62363. __decorate([
  62364. BABYLON.serialize()
  62365. ], ColorCurves.prototype, "_highlightsHue", void 0);
  62366. __decorate([
  62367. BABYLON.serialize()
  62368. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  62369. __decorate([
  62370. BABYLON.serialize()
  62371. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  62372. __decorate([
  62373. BABYLON.serialize()
  62374. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  62375. __decorate([
  62376. BABYLON.serialize()
  62377. ], ColorCurves.prototype, "_midtonesHue", void 0);
  62378. __decorate([
  62379. BABYLON.serialize()
  62380. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  62381. __decorate([
  62382. BABYLON.serialize()
  62383. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  62384. __decorate([
  62385. BABYLON.serialize()
  62386. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  62387. BABYLON.ColorCurves = ColorCurves;
  62388. })(BABYLON || (BABYLON = {}));
  62389. //# sourceMappingURL=babylon.colorCurves.js.map
  62390. var BABYLON;
  62391. (function (BABYLON) {
  62392. var Octree = (function () {
  62393. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  62394. if (maxDepth === void 0) { maxDepth = 2; }
  62395. this.maxDepth = maxDepth;
  62396. this.dynamicContent = new Array();
  62397. this._maxBlockCapacity = maxBlockCapacity || 64;
  62398. this._selectionContent = new BABYLON.SmartArray(1024);
  62399. this._creationFunc = creationFunc;
  62400. }
  62401. // Methods
  62402. Octree.prototype.update = function (worldMin, worldMax, entries) {
  62403. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  62404. };
  62405. Octree.prototype.addMesh = function (entry) {
  62406. for (var index = 0; index < this.blocks.length; index++) {
  62407. var block = this.blocks[index];
  62408. block.addEntry(entry);
  62409. }
  62410. };
  62411. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  62412. this._selectionContent.reset();
  62413. for (var index = 0; index < this.blocks.length; index++) {
  62414. var block = this.blocks[index];
  62415. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  62416. }
  62417. if (allowDuplicate) {
  62418. this._selectionContent.concat(this.dynamicContent);
  62419. }
  62420. else {
  62421. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  62422. }
  62423. return this._selectionContent;
  62424. };
  62425. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  62426. this._selectionContent.reset();
  62427. for (var index = 0; index < this.blocks.length; index++) {
  62428. var block = this.blocks[index];
  62429. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  62430. }
  62431. if (allowDuplicate) {
  62432. this._selectionContent.concat(this.dynamicContent);
  62433. }
  62434. else {
  62435. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  62436. }
  62437. return this._selectionContent;
  62438. };
  62439. Octree.prototype.intersectsRay = function (ray) {
  62440. this._selectionContent.reset();
  62441. for (var index = 0; index < this.blocks.length; index++) {
  62442. var block = this.blocks[index];
  62443. block.intersectsRay(ray, this._selectionContent);
  62444. }
  62445. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  62446. return this._selectionContent;
  62447. };
  62448. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  62449. target.blocks = new Array();
  62450. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  62451. // Segmenting space
  62452. for (var x = 0; x < 2; x++) {
  62453. for (var y = 0; y < 2; y++) {
  62454. for (var z = 0; z < 2; z++) {
  62455. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  62456. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  62457. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  62458. block.addEntries(entries);
  62459. target.blocks.push(block);
  62460. }
  62461. }
  62462. }
  62463. };
  62464. return Octree;
  62465. }());
  62466. Octree.CreationFuncForMeshes = function (entry, block) {
  62467. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  62468. block.entries.push(entry);
  62469. }
  62470. };
  62471. Octree.CreationFuncForSubMeshes = function (entry, block) {
  62472. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  62473. block.entries.push(entry);
  62474. }
  62475. };
  62476. BABYLON.Octree = Octree;
  62477. })(BABYLON || (BABYLON = {}));
  62478. //# sourceMappingURL=babylon.octree.js.map
  62479. var BABYLON;
  62480. (function (BABYLON) {
  62481. var OctreeBlock = (function () {
  62482. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  62483. this.entries = new Array();
  62484. this._boundingVectors = new Array();
  62485. this._capacity = capacity;
  62486. this._depth = depth;
  62487. this._maxDepth = maxDepth;
  62488. this._creationFunc = creationFunc;
  62489. this._minPoint = minPoint;
  62490. this._maxPoint = maxPoint;
  62491. this._boundingVectors.push(minPoint.clone());
  62492. this._boundingVectors.push(maxPoint.clone());
  62493. this._boundingVectors.push(minPoint.clone());
  62494. this._boundingVectors[2].x = maxPoint.x;
  62495. this._boundingVectors.push(minPoint.clone());
  62496. this._boundingVectors[3].y = maxPoint.y;
  62497. this._boundingVectors.push(minPoint.clone());
  62498. this._boundingVectors[4].z = maxPoint.z;
  62499. this._boundingVectors.push(maxPoint.clone());
  62500. this._boundingVectors[5].z = minPoint.z;
  62501. this._boundingVectors.push(maxPoint.clone());
  62502. this._boundingVectors[6].x = minPoint.x;
  62503. this._boundingVectors.push(maxPoint.clone());
  62504. this._boundingVectors[7].y = minPoint.y;
  62505. }
  62506. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  62507. // Property
  62508. get: function () {
  62509. return this._capacity;
  62510. },
  62511. enumerable: true,
  62512. configurable: true
  62513. });
  62514. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  62515. get: function () {
  62516. return this._minPoint;
  62517. },
  62518. enumerable: true,
  62519. configurable: true
  62520. });
  62521. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  62522. get: function () {
  62523. return this._maxPoint;
  62524. },
  62525. enumerable: true,
  62526. configurable: true
  62527. });
  62528. // Methods
  62529. OctreeBlock.prototype.addEntry = function (entry) {
  62530. if (this.blocks) {
  62531. for (var index = 0; index < this.blocks.length; index++) {
  62532. var block = this.blocks[index];
  62533. block.addEntry(entry);
  62534. }
  62535. return;
  62536. }
  62537. this._creationFunc(entry, this);
  62538. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  62539. this.createInnerBlocks();
  62540. }
  62541. };
  62542. OctreeBlock.prototype.addEntries = function (entries) {
  62543. for (var index = 0; index < entries.length; index++) {
  62544. var mesh = entries[index];
  62545. this.addEntry(mesh);
  62546. }
  62547. };
  62548. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  62549. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  62550. if (this.blocks) {
  62551. for (var index = 0; index < this.blocks.length; index++) {
  62552. var block = this.blocks[index];
  62553. block.select(frustumPlanes, selection, allowDuplicate);
  62554. }
  62555. return;
  62556. }
  62557. if (allowDuplicate) {
  62558. selection.concat(this.entries);
  62559. }
  62560. else {
  62561. selection.concatWithNoDuplicate(this.entries);
  62562. }
  62563. }
  62564. };
  62565. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  62566. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  62567. if (this.blocks) {
  62568. for (var index = 0; index < this.blocks.length; index++) {
  62569. var block = this.blocks[index];
  62570. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  62571. }
  62572. return;
  62573. }
  62574. if (allowDuplicate) {
  62575. selection.concat(this.entries);
  62576. }
  62577. else {
  62578. selection.concatWithNoDuplicate(this.entries);
  62579. }
  62580. }
  62581. };
  62582. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  62583. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  62584. if (this.blocks) {
  62585. for (var index = 0; index < this.blocks.length; index++) {
  62586. var block = this.blocks[index];
  62587. block.intersectsRay(ray, selection);
  62588. }
  62589. return;
  62590. }
  62591. selection.concatWithNoDuplicate(this.entries);
  62592. }
  62593. };
  62594. OctreeBlock.prototype.createInnerBlocks = function () {
  62595. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  62596. };
  62597. return OctreeBlock;
  62598. }());
  62599. BABYLON.OctreeBlock = OctreeBlock;
  62600. })(BABYLON || (BABYLON = {}));
  62601. //# sourceMappingURL=babylon.octreeBlock.js.map
  62602. var BABYLON;
  62603. (function (BABYLON) {
  62604. var SIMDVector3 = (function () {
  62605. function SIMDVector3() {
  62606. }
  62607. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  62608. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  62609. };
  62610. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  62611. var m = transformation.m;
  62612. var m0 = SIMD.Float32x4.load(m, 0);
  62613. var m1 = SIMD.Float32x4.load(m, 4);
  62614. var m2 = SIMD.Float32x4.load(m, 8);
  62615. var m3 = SIMD.Float32x4.load(m, 12);
  62616. 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));
  62617. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  62618. result.x = SIMD.Float32x4.extractLane(r, 0);
  62619. result.y = SIMD.Float32x4.extractLane(r, 1);
  62620. result.z = SIMD.Float32x4.extractLane(r, 2);
  62621. };
  62622. return SIMDVector3;
  62623. }());
  62624. var SIMDMatrix = (function () {
  62625. function SIMDMatrix() {
  62626. }
  62627. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  62628. var tm = this.m;
  62629. var om = other.m;
  62630. var m0 = SIMD.Float32x4.load(om, 0);
  62631. var m1 = SIMD.Float32x4.load(om, 4);
  62632. var m2 = SIMD.Float32x4.load(om, 8);
  62633. var m3 = SIMD.Float32x4.load(om, 12);
  62634. for (var i = 0; i < 16; i += 4) {
  62635. 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)))));
  62636. }
  62637. return this;
  62638. };
  62639. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  62640. var src = this.m;
  62641. var dest = other.m;
  62642. // Load the 4 rows
  62643. var src0 = SIMD.Float32x4.load(src, 0);
  62644. var src1 = SIMD.Float32x4.load(src, 4);
  62645. var src2 = SIMD.Float32x4.load(src, 8);
  62646. var src3 = SIMD.Float32x4.load(src, 12);
  62647. // Transpose the source matrix. Sort of. Not a true transpose operation
  62648. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  62649. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  62650. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  62651. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  62652. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  62653. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  62654. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  62655. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  62656. // This is a true transposition, but it will lead to an incorrect result
  62657. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  62658. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  62659. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  62660. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  62661. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  62662. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  62663. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  62664. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  62665. // ----
  62666. tmp1 = SIMD.Float32x4.mul(row2, row3);
  62667. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62668. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  62669. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  62670. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62671. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  62672. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  62673. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  62674. // ----
  62675. tmp1 = SIMD.Float32x4.mul(row1, row2);
  62676. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62677. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  62678. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  62679. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62680. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  62681. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  62682. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  62683. // ----
  62684. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  62685. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62686. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  62687. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  62688. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  62689. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62690. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  62691. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  62692. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  62693. // ----
  62694. tmp1 = SIMD.Float32x4.mul(row0, row1);
  62695. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62696. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  62697. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  62698. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62699. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  62700. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  62701. // ----
  62702. tmp1 = SIMD.Float32x4.mul(row0, row3);
  62703. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62704. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  62705. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  62706. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62707. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  62708. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  62709. // ----
  62710. tmp1 = SIMD.Float32x4.mul(row0, row2);
  62711. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  62712. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  62713. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  62714. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  62715. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  62716. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  62717. // Compute determinant
  62718. var det = SIMD.Float32x4.mul(row0, minor0);
  62719. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  62720. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  62721. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  62722. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  62723. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  62724. // These shuffles aren't necessary if the faulty transposition is done
  62725. // up at the top of this function.
  62726. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  62727. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  62728. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  62729. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  62730. // Compute final values by multiplying with 1/det
  62731. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  62732. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  62733. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  62734. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  62735. return this;
  62736. };
  62737. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  62738. var out = result.m;
  62739. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  62740. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  62741. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  62742. // cc.kmVec3Subtract(f, pCenter, pEye);
  62743. var f = SIMD.Float32x4.sub(center, eye);
  62744. // cc.kmVec3Normalize(f, f);
  62745. var tmp = SIMD.Float32x4.mul(f, f);
  62746. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  62747. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  62748. // cc.kmVec3Assign(up, pUp);
  62749. // cc.kmVec3Normalize(up, up);
  62750. tmp = SIMD.Float32x4.mul(up, up);
  62751. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  62752. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  62753. // cc.kmVec3Cross(s, f, up);
  62754. 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)));
  62755. // cc.kmVec3Normalize(s, s);
  62756. tmp = SIMD.Float32x4.mul(s, s);
  62757. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  62758. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  62759. // cc.kmVec3Cross(u, s, f);
  62760. 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)));
  62761. // cc.kmVec3Normalize(s, s);
  62762. tmp = SIMD.Float32x4.mul(s, s);
  62763. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  62764. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  62765. var zero = SIMD.Float32x4.splat(0.0);
  62766. s = SIMD.Float32x4.neg(s);
  62767. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  62768. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  62769. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  62770. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  62771. 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);
  62772. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  62773. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  62774. 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)))));
  62775. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  62776. 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)))));
  62777. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  62778. 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)))));
  62779. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  62780. 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)))));
  62781. };
  62782. return SIMDMatrix;
  62783. }());
  62784. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  62785. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  62786. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  62787. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  62788. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  62789. var SIMDHelper = (function () {
  62790. function SIMDHelper() {
  62791. }
  62792. Object.defineProperty(SIMDHelper, "IsEnabled", {
  62793. get: function () {
  62794. return SIMDHelper._isEnabled;
  62795. },
  62796. enumerable: true,
  62797. configurable: true
  62798. });
  62799. SIMDHelper.DisableSIMD = function () {
  62800. // Replace functions
  62801. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  62802. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  62803. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  62804. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  62805. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  62806. SIMDHelper._isEnabled = false;
  62807. };
  62808. SIMDHelper.EnableSIMD = function () {
  62809. if (self.SIMD === undefined) {
  62810. return;
  62811. }
  62812. // check if polyfills needed
  62813. if (!self.Math.fround) {
  62814. self.Math.fround = (function (array) { return function (x) {
  62815. return array[0] = x, array[0];
  62816. }; })(new Float32Array(1));
  62817. }
  62818. if (!self.Math.imul) {
  62819. self.Math.imul = function (a, b) {
  62820. var ah = (a >>> 16) & 0xffff;
  62821. var al = a & 0xffff;
  62822. var bh = (b >>> 16) & 0xffff;
  62823. var bl = b & 0xffff;
  62824. // the shift by 0 fixes the sign on the high part
  62825. // the final |0 converts the unsigned value into a signed value
  62826. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  62827. };
  62828. }
  62829. // Replace functions
  62830. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  62831. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  62832. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  62833. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  62834. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  62835. SIMDHelper._isEnabled = true;
  62836. };
  62837. return SIMDHelper;
  62838. }());
  62839. SIMDHelper._isEnabled = false;
  62840. BABYLON.SIMDHelper = SIMDHelper;
  62841. })(BABYLON || (BABYLON = {}));
  62842. //# sourceMappingURL=babylon.math.SIMD.js.map
  62843. var BABYLON;
  62844. (function (BABYLON) {
  62845. var VRDistortionCorrectionPostProcess = (function (_super) {
  62846. __extends(VRDistortionCorrectionPostProcess, _super);
  62847. //ANY
  62848. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  62849. var _this = _super.call(this, name, "vrDistortionCorrection", [
  62850. 'LensCenter',
  62851. 'Scale',
  62852. 'ScaleIn',
  62853. 'HmdWarpParam'
  62854. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  62855. _this._isRightEye = isRightEye;
  62856. _this._distortionFactors = vrMetrics.distortionK;
  62857. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  62858. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  62859. _this.onSizeChangedObservable.add(function () {
  62860. _this.aspectRatio = _this.width * .5 / _this.height;
  62861. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  62862. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  62863. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  62864. });
  62865. _this.onApplyObservable.add(function (effect) {
  62866. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  62867. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  62868. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  62869. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  62870. });
  62871. return _this;
  62872. }
  62873. return VRDistortionCorrectionPostProcess;
  62874. }(BABYLON.PostProcess));
  62875. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  62876. })(BABYLON || (BABYLON = {}));
  62877. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  62878. var BABYLON;
  62879. (function (BABYLON) {
  62880. var AnaglyphPostProcess = (function (_super) {
  62881. __extends(AnaglyphPostProcess, _super);
  62882. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  62883. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  62884. _this._passedProcess = rigCameras[0]._rigPostProcess;
  62885. _this.onApplyObservable.add(function (effect) {
  62886. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  62887. });
  62888. return _this;
  62889. }
  62890. return AnaglyphPostProcess;
  62891. }(BABYLON.PostProcess));
  62892. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  62893. })(BABYLON || (BABYLON = {}));
  62894. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  62895. var BABYLON;
  62896. (function (BABYLON) {
  62897. var StereoscopicInterlacePostProcess = (function (_super) {
  62898. __extends(StereoscopicInterlacePostProcess, _super);
  62899. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  62900. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  62901. _this._passedProcess = rigCameras[0]._rigPostProcess;
  62902. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  62903. _this.onSizeChangedObservable.add(function () {
  62904. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  62905. });
  62906. _this.onApplyObservable.add(function (effect) {
  62907. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  62908. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  62909. });
  62910. return _this;
  62911. }
  62912. return StereoscopicInterlacePostProcess;
  62913. }(BABYLON.PostProcess));
  62914. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  62915. })(BABYLON || (BABYLON = {}));
  62916. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  62917. var BABYLON;
  62918. (function (BABYLON) {
  62919. var FreeCameraDeviceOrientationInput = (function () {
  62920. function FreeCameraDeviceOrientationInput() {
  62921. var _this = this;
  62922. this._screenOrientationAngle = 0;
  62923. this._screenQuaternion = new BABYLON.Quaternion();
  62924. this._alpha = 0;
  62925. this._beta = 0;
  62926. this._gamma = 0;
  62927. this._orientationChanged = function () {
  62928. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  62929. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  62930. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  62931. };
  62932. this._deviceOrientation = function (evt) {
  62933. _this._alpha = evt.alpha;
  62934. _this._beta = evt.beta;
  62935. _this._gamma = evt.gamma;
  62936. };
  62937. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  62938. this._orientationChanged();
  62939. }
  62940. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  62941. get: function () {
  62942. return this._camera;
  62943. },
  62944. set: function (camera) {
  62945. this._camera = camera;
  62946. if (!this._camera.rotationQuaternion)
  62947. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  62948. },
  62949. enumerable: true,
  62950. configurable: true
  62951. });
  62952. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  62953. window.addEventListener("orientationchange", this._orientationChanged);
  62954. window.addEventListener("deviceorientation", this._deviceOrientation);
  62955. //In certain cases, the attach control is called AFTER orientation was changed,
  62956. //So this is needed.
  62957. this._orientationChanged();
  62958. };
  62959. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  62960. window.removeEventListener("orientationchange", this._orientationChanged);
  62961. window.removeEventListener("deviceorientation", this._deviceOrientation);
  62962. };
  62963. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  62964. //if no device orientation provided, don't update the rotation.
  62965. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  62966. if (!this._alpha)
  62967. return;
  62968. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  62969. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  62970. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  62971. //Mirror on XY Plane
  62972. this._camera.rotationQuaternion.z *= -1;
  62973. this._camera.rotationQuaternion.w *= -1;
  62974. };
  62975. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  62976. return "FreeCameraDeviceOrientationInput";
  62977. };
  62978. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  62979. return "deviceOrientation";
  62980. };
  62981. return FreeCameraDeviceOrientationInput;
  62982. }());
  62983. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  62984. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  62985. })(BABYLON || (BABYLON = {}));
  62986. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  62987. var BABYLON;
  62988. (function (BABYLON) {
  62989. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  62990. function ArcRotateCameraVRDeviceOrientationInput() {
  62991. this.alphaCorrection = 1;
  62992. this.betaCorrection = 1;
  62993. this.gammaCorrection = 1;
  62994. this._alpha = 0;
  62995. this._beta = 0;
  62996. this._gamma = 0;
  62997. this._dirty = false;
  62998. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  62999. }
  63000. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  63001. this.camera.attachControl(element, noPreventDefault);
  63002. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  63003. };
  63004. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  63005. var camera = this.camera;
  63006. this._alpha = +evt.alpha | 0;
  63007. this._beta = +evt.beta | 0;
  63008. this._gamma = +evt.gamma | 0;
  63009. this._dirty = true;
  63010. };
  63011. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  63012. if (this._dirty) {
  63013. this._dirty = false;
  63014. if (this._gamma < 0) {
  63015. this._gamma = 180 + this._gamma;
  63016. }
  63017. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  63018. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  63019. }
  63020. };
  63021. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  63022. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  63023. };
  63024. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  63025. return "ArcRotateCameraVRDeviceOrientationInput";
  63026. };
  63027. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  63028. return "VRDeviceOrientation";
  63029. };
  63030. return ArcRotateCameraVRDeviceOrientationInput;
  63031. }());
  63032. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  63033. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  63034. })(BABYLON || (BABYLON = {}));
  63035. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  63036. var BABYLON;
  63037. (function (BABYLON) {
  63038. var VRCameraMetrics = (function () {
  63039. function VRCameraMetrics() {
  63040. this.compensateDistortion = true;
  63041. }
  63042. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  63043. get: function () {
  63044. return this.hResolution / (2 * this.vResolution);
  63045. },
  63046. enumerable: true,
  63047. configurable: true
  63048. });
  63049. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  63050. get: function () {
  63051. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  63052. },
  63053. enumerable: true,
  63054. configurable: true
  63055. });
  63056. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  63057. get: function () {
  63058. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  63059. var h = (4 * meters) / this.hScreenSize;
  63060. return BABYLON.Matrix.Translation(h, 0, 0);
  63061. },
  63062. enumerable: true,
  63063. configurable: true
  63064. });
  63065. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  63066. get: function () {
  63067. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  63068. var h = (4 * meters) / this.hScreenSize;
  63069. return BABYLON.Matrix.Translation(-h, 0, 0);
  63070. },
  63071. enumerable: true,
  63072. configurable: true
  63073. });
  63074. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  63075. get: function () {
  63076. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  63077. },
  63078. enumerable: true,
  63079. configurable: true
  63080. });
  63081. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  63082. get: function () {
  63083. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  63084. },
  63085. enumerable: true,
  63086. configurable: true
  63087. });
  63088. VRCameraMetrics.GetDefault = function () {
  63089. var result = new VRCameraMetrics();
  63090. result.hResolution = 1280;
  63091. result.vResolution = 800;
  63092. result.hScreenSize = 0.149759993;
  63093. result.vScreenSize = 0.0935999975;
  63094. result.vScreenCenter = 0.0467999987;
  63095. result.eyeToScreenDistance = 0.0410000011;
  63096. result.lensSeparationDistance = 0.0635000020;
  63097. result.interpupillaryDistance = 0.0640000030;
  63098. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  63099. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  63100. result.postProcessScaleFactor = 1.714605507808412;
  63101. result.lensCenterOffset = 0.151976421;
  63102. return result;
  63103. };
  63104. return VRCameraMetrics;
  63105. }());
  63106. BABYLON.VRCameraMetrics = VRCameraMetrics;
  63107. })(BABYLON || (BABYLON = {}));
  63108. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  63109. var BABYLON;
  63110. (function (BABYLON) {
  63111. var WebVRFreeCamera = (function (_super) {
  63112. __extends(WebVRFreeCamera, _super);
  63113. function WebVRFreeCamera(name, position, scene, webVROptions) {
  63114. if (webVROptions === void 0) { webVROptions = {}; }
  63115. var _this = _super.call(this, name, position, scene) || this;
  63116. _this.webVROptions = webVROptions;
  63117. _this._vrDevice = null;
  63118. _this.rawPose = null;
  63119. _this._vrEnabled = false;
  63120. _this._specsVersion = 1.1;
  63121. _this._attached = false;
  63122. _this._positionOffset = BABYLON.Vector3.Zero();
  63123. _this._descendants = [];
  63124. _this.devicePosition = BABYLON.Vector3.Zero();
  63125. _this.deviceScaleFactor = 1;
  63126. _this.controllers = [];
  63127. _this.nonVRControllers = [];
  63128. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  63129. //legacy support - the compensation boolean was removed.
  63130. if (arguments.length === 5) {
  63131. _this.webVROptions = arguments[4];
  63132. }
  63133. // default webVR options
  63134. if (_this.webVROptions.trackPosition == undefined) {
  63135. _this.webVROptions.trackPosition = true;
  63136. }
  63137. if (_this.webVROptions.controllerMeshes == undefined) {
  63138. _this.webVROptions.controllerMeshes = true;
  63139. }
  63140. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  63141. _this.webVROptions.defaultLightningOnControllers = true;
  63142. }
  63143. _this.rotationQuaternion = new BABYLON.Quaternion();
  63144. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63145. if (_this.webVROptions && _this.webVROptions.positionScale) {
  63146. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  63147. }
  63148. //enable VR
  63149. _this.getEngine().initWebVR();
  63150. //check specs version
  63151. if (!window.VRFrameData) {
  63152. _this._specsVersion = 1.0;
  63153. _this._frameData = {};
  63154. }
  63155. else {
  63156. _this._frameData = new VRFrameData();
  63157. }
  63158. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  63159. if (!device) {
  63160. return;
  63161. }
  63162. _this._vrEnabled = true;
  63163. _this._vrDevice = device;
  63164. //reset the rig parameters.
  63165. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  63166. if (_this._attached) {
  63167. _this.getEngine().enableVR(_this._vrDevice);
  63168. }
  63169. });
  63170. // try to attach the controllers, if found.
  63171. _this.initControllers();
  63172. /**
  63173. * The idea behind the following lines:
  63174. * objects that have the camera as parent should actually have the rig cameras as a parent.
  63175. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  63176. * the second will not show it correctly.
  63177. *
  63178. * To solve this - each object that has the camera as parent will be added to a protected array.
  63179. * When the rig camera renders, it will take this array and set all of those to be its children.
  63180. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  63181. * Amazing!
  63182. */
  63183. scene.onBeforeCameraRenderObservable.add(function (camera) {
  63184. if (camera.parent === _this && _this.rigParenting) {
  63185. _this._descendants = _this.getDescendants(true, function (n) {
  63186. // don't take the cameras or the controllers!
  63187. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  63188. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  63189. return !isController && !isRigCamera;
  63190. });
  63191. _this._descendants.forEach(function (node) {
  63192. node.parent = camera;
  63193. });
  63194. }
  63195. });
  63196. scene.onAfterCameraRenderObservable.add(function (camera) {
  63197. if (camera.parent === _this && _this.rigParenting) {
  63198. _this._descendants.forEach(function (node) {
  63199. node.parent = _this;
  63200. });
  63201. }
  63202. });
  63203. return _this;
  63204. }
  63205. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  63206. set: function (callback) {
  63207. this._onControllersAttached = callback;
  63208. // after setting - if the controllers are already set, execute the callback.
  63209. if (this.controllers.length >= 2) {
  63210. callback(this.controllers);
  63211. }
  63212. },
  63213. enumerable: true,
  63214. configurable: true
  63215. });
  63216. Object.defineProperty(WebVRFreeCamera.prototype, "onNonVRControllerAttached", {
  63217. set: function (callback) {
  63218. this._onNonVRControllerAttached = callback;
  63219. this.nonVRControllers.forEach(function (controller) {
  63220. callback(controller);
  63221. });
  63222. },
  63223. enumerable: true,
  63224. configurable: true
  63225. });
  63226. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  63227. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  63228. var gp = _a[_i];
  63229. if (gp.hand === name) {
  63230. return gp;
  63231. }
  63232. }
  63233. return undefined;
  63234. };
  63235. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  63236. get: function () {
  63237. if (!this._leftController) {
  63238. this._leftController = this.getControllerByName("left");
  63239. }
  63240. return this._leftController;
  63241. },
  63242. enumerable: true,
  63243. configurable: true
  63244. });
  63245. ;
  63246. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  63247. get: function () {
  63248. if (!this._rightController) {
  63249. this._rightController = this.getControllerByName("right");
  63250. }
  63251. return this._rightController;
  63252. },
  63253. enumerable: true,
  63254. configurable: true
  63255. });
  63256. ;
  63257. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  63258. if (length === void 0) { length = 100; }
  63259. if (this.leftCamera) {
  63260. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  63261. }
  63262. else {
  63263. return _super.prototype.getForwardRay.call(this, length);
  63264. }
  63265. };
  63266. WebVRFreeCamera.prototype._checkInputs = function () {
  63267. if (this._vrEnabled) {
  63268. if (this._specsVersion === 1.1) {
  63269. this._vrDevice.getFrameData(this._frameData);
  63270. }
  63271. else {
  63272. //backwards comp
  63273. var pose = this._vrDevice.getPose();
  63274. this._frameData.pose = pose;
  63275. // calculate view and projection matrix
  63276. }
  63277. this.updateFromDevice(this._frameData.pose);
  63278. }
  63279. _super.prototype._checkInputs.call(this);
  63280. };
  63281. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  63282. if (poseData && poseData.orientation) {
  63283. this.rawPose = poseData;
  63284. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  63285. if (this.getScene().useRightHandedSystem) {
  63286. this.deviceRotationQuaternion.z *= -1;
  63287. this.deviceRotationQuaternion.w *= -1;
  63288. }
  63289. if (this.webVROptions.trackPosition && this.rawPose.position) {
  63290. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  63291. if (this.getScene().useRightHandedSystem) {
  63292. this.devicePosition.z *= -1;
  63293. }
  63294. }
  63295. }
  63296. };
  63297. /**
  63298. * WebVR's attach control will start broadcasting frames to the device.
  63299. * Note that in certain browsers (chrome for example) this function must be called
  63300. * within a user-interaction callback. Example:
  63301. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  63302. *
  63303. * @param {HTMLElement} element
  63304. * @param {boolean} [noPreventDefault]
  63305. *
  63306. * @memberOf WebVRFreeCamera
  63307. */
  63308. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  63309. _super.prototype.attachControl.call(this, element, noPreventDefault);
  63310. this._attached = true;
  63311. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  63312. if (this._vrEnabled) {
  63313. this.getEngine().enableVR(this._vrDevice);
  63314. }
  63315. };
  63316. WebVRFreeCamera.prototype.detachControl = function (element) {
  63317. _super.prototype.detachControl.call(this, element);
  63318. this._vrEnabled = false;
  63319. this._attached = false;
  63320. this.getEngine().disableVR();
  63321. };
  63322. WebVRFreeCamera.prototype.getClassName = function () {
  63323. return "WebVRFreeCamera";
  63324. };
  63325. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  63326. //uses the vrDisplay's "resetPose()".
  63327. //pitch and roll won't be affected.
  63328. this._vrDevice.resetPose();
  63329. };
  63330. WebVRFreeCamera.prototype._updateRigCameras = function () {
  63331. var camLeft = this._rigCameras[0];
  63332. var camRight = this._rigCameras[1];
  63333. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63334. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63335. camLeft.position.copyFrom(this.devicePosition);
  63336. camRight.position.copyFrom(this.devicePosition);
  63337. };
  63338. /**
  63339. * This function is called by the two RIG cameras.
  63340. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  63341. */
  63342. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  63343. var _this = this;
  63344. //WebVR 1.0
  63345. if (this._cameraRigParams["specs"] === 1.0) {
  63346. this._updateCameraRotationMatrix();
  63347. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  63348. // Computing target and final matrix
  63349. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  63350. if (this.getScene().useRightHandedSystem) {
  63351. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  63352. }
  63353. else {
  63354. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  63355. }
  63356. //now move the eye in the right direction
  63357. var eyeParams = this._cameraRigParams["eyeParameters"];
  63358. var offset = eyeParams.offset;
  63359. // it will actually always be 0, but just in case
  63360. if (this.getScene().useRightHandedSystem) {
  63361. offset[2] *= -1;
  63362. }
  63363. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  63364. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  63365. }
  63366. else {
  63367. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  63368. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  63369. if (!this.getScene().useRightHandedSystem) {
  63370. [2, 6, 8, 9, 14].forEach(function (num) {
  63371. _this._webvrViewMatrix.m[num] *= -1;
  63372. });
  63373. }
  63374. // update the camera rotation matrix
  63375. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  63376. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  63377. // Computing target and final matrix
  63378. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  63379. }
  63380. var parentCamera = this._cameraRigParams["parentCamera"];
  63381. // should the view matrix be updated with scale and position offset?
  63382. if (parentCamera.deviceScaleFactor !== 1) {
  63383. this._webvrViewMatrix.invert();
  63384. // scale the position, if set
  63385. if (parentCamera.deviceScaleFactor) {
  63386. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  63387. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  63388. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  63389. }
  63390. this._webvrViewMatrix.invert();
  63391. }
  63392. return this._webvrViewMatrix;
  63393. };
  63394. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  63395. var _this = this;
  63396. if (this._cameraRigParams["specs"] === 1.0) {
  63397. var eyeParams = this._cameraRigParams["eyeParameters"];
  63398. // deprecated!!
  63399. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  63400. }
  63401. else {
  63402. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  63403. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  63404. //babylon compatible matrix
  63405. if (!this.getScene().useRightHandedSystem) {
  63406. [8, 9, 10, 11].forEach(function (num) {
  63407. _this._projectionMatrix.m[num] *= -1;
  63408. });
  63409. }
  63410. }
  63411. return this._projectionMatrix;
  63412. };
  63413. WebVRFreeCamera.prototype.initControllers = function () {
  63414. var _this = this;
  63415. this.controllers = [];
  63416. new BABYLON.Gamepads(function (gp) {
  63417. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  63418. var webVrController = gp;
  63419. if (_this.webVROptions.controllerMeshes) {
  63420. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  63421. if (_this.webVROptions.defaultLightningOnControllers) {
  63422. if (!_this._lightOnControllers) {
  63423. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  63424. }
  63425. loadedMesh.getChildren().forEach(function (mesh) {
  63426. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  63427. });
  63428. }
  63429. });
  63430. }
  63431. webVrController.attachToPoseControlledCamera(_this);
  63432. // since this is async - sanity check. Is the controller already stored?
  63433. if (_this.controllers.indexOf(webVrController) === -1) {
  63434. //add to the controllers array
  63435. _this.controllers.push(webVrController);
  63436. //did we find enough controllers? Great! let the developer know.
  63437. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  63438. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  63439. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  63440. // So we're overriding setting left & right manually to be sure
  63441. var firstViveWandDetected = false;
  63442. for (var i = 0; i < _this.controllers.length; i++) {
  63443. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  63444. if (!firstViveWandDetected) {
  63445. firstViveWandDetected = true;
  63446. _this.controllers[i].hand = "left";
  63447. }
  63448. else {
  63449. _this.controllers[i].hand = "right";
  63450. }
  63451. }
  63452. }
  63453. _this._onControllersAttached(_this.controllers);
  63454. }
  63455. }
  63456. }
  63457. else {
  63458. _this.nonVRControllers.push(gp);
  63459. if (_this._onNonVRControllerAttached) {
  63460. _this._onNonVRControllerAttached(gp);
  63461. }
  63462. }
  63463. });
  63464. };
  63465. return WebVRFreeCamera;
  63466. }(BABYLON.FreeCamera));
  63467. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  63468. })(BABYLON || (BABYLON = {}));
  63469. //# sourceMappingURL=babylon.webVRCamera.js.map
  63470. /// <reference path="babylon.freeCamera.ts" />
  63471. var BABYLON;
  63472. (function (BABYLON) {
  63473. // We're mainly based on the logic defined into the FreeCamera code
  63474. var DeviceOrientationCamera = (function (_super) {
  63475. __extends(DeviceOrientationCamera, _super);
  63476. function DeviceOrientationCamera(name, position, scene) {
  63477. var _this = _super.call(this, name, position, scene) || this;
  63478. _this._quaternionCache = new BABYLON.Quaternion();
  63479. _this.inputs.addDeviceOrientation();
  63480. return _this;
  63481. }
  63482. DeviceOrientationCamera.prototype.getClassName = function () {
  63483. return "DeviceOrientationCamera";
  63484. };
  63485. DeviceOrientationCamera.prototype._checkInputs = function () {
  63486. _super.prototype._checkInputs.call(this);
  63487. this._quaternionCache.copyFrom(this.rotationQuaternion);
  63488. if (this._initialQuaternion) {
  63489. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  63490. }
  63491. };
  63492. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  63493. var _this = this;
  63494. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  63495. //can only work if this camera has a rotation quaternion already.
  63496. if (!this.rotationQuaternion)
  63497. return;
  63498. if (!this._initialQuaternion) {
  63499. this._initialQuaternion = new BABYLON.Quaternion();
  63500. }
  63501. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  63502. ['x', 'y', 'z'].forEach(function (axisName) {
  63503. if (!axis[axisName]) {
  63504. _this._initialQuaternion[axisName] = 0;
  63505. }
  63506. else {
  63507. _this._initialQuaternion[axisName] *= -1;
  63508. }
  63509. });
  63510. this._initialQuaternion.normalize();
  63511. //force rotation update
  63512. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  63513. };
  63514. return DeviceOrientationCamera;
  63515. }(BABYLON.FreeCamera));
  63516. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  63517. })(BABYLON || (BABYLON = {}));
  63518. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  63519. var BABYLON;
  63520. (function (BABYLON) {
  63521. var VRDeviceOrientationFreeCamera = (function (_super) {
  63522. __extends(VRDeviceOrientationFreeCamera, _super);
  63523. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  63524. if (compensateDistortion === void 0) { compensateDistortion = true; }
  63525. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  63526. var _this = _super.call(this, name, position, scene) || this;
  63527. vrCameraMetrics.compensateDistortion = compensateDistortion;
  63528. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  63529. return _this;
  63530. }
  63531. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  63532. return "VRDeviceOrientationFreeCamera";
  63533. };
  63534. return VRDeviceOrientationFreeCamera;
  63535. }(BABYLON.DeviceOrientationCamera));
  63536. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  63537. var VRDeviceOrientationGamepadCamera = (function (_super) {
  63538. __extends(VRDeviceOrientationGamepadCamera, _super);
  63539. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  63540. if (compensateDistortion === void 0) { compensateDistortion = true; }
  63541. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  63542. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  63543. _this.inputs.addGamepad();
  63544. return _this;
  63545. }
  63546. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  63547. return "VRDeviceOrientationGamepadCamera";
  63548. };
  63549. return VRDeviceOrientationGamepadCamera;
  63550. }(VRDeviceOrientationFreeCamera));
  63551. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  63552. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  63553. __extends(VRDeviceOrientationArcRotateCamera, _super);
  63554. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  63555. if (compensateDistortion === void 0) { compensateDistortion = true; }
  63556. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  63557. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  63558. vrCameraMetrics.compensateDistortion = compensateDistortion;
  63559. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  63560. _this.inputs.addVRDeviceOrientation();
  63561. return _this;
  63562. }
  63563. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  63564. return "VRDeviceOrientationArcRotateCamera";
  63565. };
  63566. return VRDeviceOrientationArcRotateCamera;
  63567. }(BABYLON.ArcRotateCamera));
  63568. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  63569. })(BABYLON || (BABYLON = {}));
  63570. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  63571. /// <reference path="babylon.freeCamera.ts" />
  63572. /// <reference path="babylon.arcRotateCamera.ts" />
  63573. /// <reference path="babylon.gamepadCamera.ts" />
  63574. /// <reference path="babylon.universalCamera.ts" />
  63575. var BABYLON;
  63576. (function (BABYLON) {
  63577. var AnaglyphFreeCamera = (function (_super) {
  63578. __extends(AnaglyphFreeCamera, _super);
  63579. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  63580. var _this = _super.call(this, name, position, scene) || this;
  63581. _this.interaxialDistance = interaxialDistance;
  63582. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63583. return _this;
  63584. }
  63585. AnaglyphFreeCamera.prototype.getClassName = function () {
  63586. return "AnaglyphFreeCamera";
  63587. };
  63588. return AnaglyphFreeCamera;
  63589. }(BABYLON.FreeCamera));
  63590. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  63591. var AnaglyphArcRotateCamera = (function (_super) {
  63592. __extends(AnaglyphArcRotateCamera, _super);
  63593. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  63594. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  63595. _this.interaxialDistance = interaxialDistance;
  63596. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63597. return _this;
  63598. }
  63599. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  63600. return "AnaglyphArcRotateCamera";
  63601. };
  63602. return AnaglyphArcRotateCamera;
  63603. }(BABYLON.ArcRotateCamera));
  63604. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  63605. var AnaglyphGamepadCamera = (function (_super) {
  63606. __extends(AnaglyphGamepadCamera, _super);
  63607. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  63608. var _this = _super.call(this, name, position, scene) || this;
  63609. _this.interaxialDistance = interaxialDistance;
  63610. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63611. return _this;
  63612. }
  63613. AnaglyphGamepadCamera.prototype.getClassName = function () {
  63614. return "AnaglyphGamepadCamera";
  63615. };
  63616. return AnaglyphGamepadCamera;
  63617. }(BABYLON.GamepadCamera));
  63618. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  63619. var AnaglyphUniversalCamera = (function (_super) {
  63620. __extends(AnaglyphUniversalCamera, _super);
  63621. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  63622. var _this = _super.call(this, name, position, scene) || this;
  63623. _this.interaxialDistance = interaxialDistance;
  63624. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  63625. return _this;
  63626. }
  63627. AnaglyphUniversalCamera.prototype.getClassName = function () {
  63628. return "AnaglyphUniversalCamera";
  63629. };
  63630. return AnaglyphUniversalCamera;
  63631. }(BABYLON.UniversalCamera));
  63632. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  63633. var StereoscopicFreeCamera = (function (_super) {
  63634. __extends(StereoscopicFreeCamera, _super);
  63635. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  63636. var _this = _super.call(this, name, position, scene) || this;
  63637. _this.interaxialDistance = interaxialDistance;
  63638. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63639. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63640. return _this;
  63641. }
  63642. StereoscopicFreeCamera.prototype.getClassName = function () {
  63643. return "StereoscopicFreeCamera";
  63644. };
  63645. return StereoscopicFreeCamera;
  63646. }(BABYLON.FreeCamera));
  63647. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  63648. var StereoscopicArcRotateCamera = (function (_super) {
  63649. __extends(StereoscopicArcRotateCamera, _super);
  63650. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  63651. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  63652. _this.interaxialDistance = interaxialDistance;
  63653. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63654. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63655. return _this;
  63656. }
  63657. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  63658. return "StereoscopicArcRotateCamera";
  63659. };
  63660. return StereoscopicArcRotateCamera;
  63661. }(BABYLON.ArcRotateCamera));
  63662. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  63663. var StereoscopicGamepadCamera = (function (_super) {
  63664. __extends(StereoscopicGamepadCamera, _super);
  63665. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  63666. var _this = _super.call(this, name, position, scene) || this;
  63667. _this.interaxialDistance = interaxialDistance;
  63668. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63669. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63670. return _this;
  63671. }
  63672. StereoscopicGamepadCamera.prototype.getClassName = function () {
  63673. return "StereoscopicGamepadCamera";
  63674. };
  63675. return StereoscopicGamepadCamera;
  63676. }(BABYLON.GamepadCamera));
  63677. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  63678. var StereoscopicUniversalCamera = (function (_super) {
  63679. __extends(StereoscopicUniversalCamera, _super);
  63680. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  63681. var _this = _super.call(this, name, position, scene) || this;
  63682. _this.interaxialDistance = interaxialDistance;
  63683. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  63684. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  63685. return _this;
  63686. }
  63687. StereoscopicUniversalCamera.prototype.getClassName = function () {
  63688. return "StereoscopicUniversalCamera";
  63689. };
  63690. return StereoscopicUniversalCamera;
  63691. }(BABYLON.UniversalCamera));
  63692. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  63693. })(BABYLON || (BABYLON = {}));
  63694. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  63695. // Mainly based on these 2 articles :
  63696. // 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
  63697. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  63698. var BABYLON;
  63699. (function (BABYLON) {
  63700. var JoystickAxis;
  63701. (function (JoystickAxis) {
  63702. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  63703. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  63704. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  63705. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  63706. var VirtualJoystick = (function () {
  63707. function VirtualJoystick(leftJoystick) {
  63708. var _this = this;
  63709. if (leftJoystick) {
  63710. this._leftJoystick = true;
  63711. }
  63712. else {
  63713. this._leftJoystick = false;
  63714. }
  63715. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  63716. VirtualJoystick._globalJoystickIndex++;
  63717. // By default left & right arrow keys are moving the X
  63718. // and up & down keys are moving the Y
  63719. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  63720. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  63721. this.reverseLeftRight = false;
  63722. this.reverseUpDown = false;
  63723. // collections of pointers
  63724. this._touches = new BABYLON.StringDictionary();
  63725. this.deltaPosition = BABYLON.Vector3.Zero();
  63726. this._joystickSensibility = 25;
  63727. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  63728. this._rotationSpeed = 25;
  63729. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  63730. this._rotateOnAxisRelativeToMesh = false;
  63731. this._onResize = function (evt) {
  63732. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  63733. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  63734. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  63735. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  63736. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  63737. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  63738. };
  63739. // injecting a canvas element on top of the canvas 3D game
  63740. if (!VirtualJoystick.vjCanvas) {
  63741. window.addEventListener("resize", this._onResize, false);
  63742. VirtualJoystick.vjCanvas = document.createElement("canvas");
  63743. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  63744. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  63745. VirtualJoystick.vjCanvas.width = window.innerWidth;
  63746. VirtualJoystick.vjCanvas.height = window.innerHeight;
  63747. VirtualJoystick.vjCanvas.style.width = "100%";
  63748. VirtualJoystick.vjCanvas.style.height = "100%";
  63749. VirtualJoystick.vjCanvas.style.position = "absolute";
  63750. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  63751. VirtualJoystick.vjCanvas.style.top = "0px";
  63752. VirtualJoystick.vjCanvas.style.left = "0px";
  63753. VirtualJoystick.vjCanvas.style.zIndex = "5";
  63754. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  63755. // Support for jQuery PEP polyfill
  63756. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  63757. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  63758. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  63759. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  63760. document.body.appendChild(VirtualJoystick.vjCanvas);
  63761. }
  63762. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  63763. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  63764. this.pressed = false;
  63765. // default joystick color
  63766. this._joystickColor = "cyan";
  63767. this._joystickPointerID = -1;
  63768. // current joystick position
  63769. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  63770. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  63771. // origin joystick position
  63772. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  63773. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  63774. this._onPointerDownHandlerRef = function (evt) {
  63775. _this._onPointerDown(evt);
  63776. };
  63777. this._onPointerMoveHandlerRef = function (evt) {
  63778. _this._onPointerMove(evt);
  63779. };
  63780. this._onPointerOutHandlerRef = function (evt) {
  63781. _this._onPointerUp(evt);
  63782. };
  63783. this._onPointerUpHandlerRef = function (evt) {
  63784. _this._onPointerUp(evt);
  63785. };
  63786. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  63787. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  63788. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  63789. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  63790. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  63791. evt.preventDefault(); // Disables system menu
  63792. }, false);
  63793. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  63794. }
  63795. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  63796. this._joystickSensibility = newJoystickSensibility;
  63797. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  63798. };
  63799. VirtualJoystick.prototype._onPointerDown = function (e) {
  63800. var positionOnScreenCondition;
  63801. e.preventDefault();
  63802. if (this._leftJoystick === true) {
  63803. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  63804. }
  63805. else {
  63806. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  63807. }
  63808. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  63809. // First contact will be dedicated to the virtual joystick
  63810. this._joystickPointerID = e.pointerId;
  63811. this._joystickPointerStartPos.x = e.clientX;
  63812. this._joystickPointerStartPos.y = e.clientY;
  63813. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  63814. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  63815. this._deltaJoystickVector.x = 0;
  63816. this._deltaJoystickVector.y = 0;
  63817. this.pressed = true;
  63818. this._touches.add(e.pointerId.toString(), e);
  63819. }
  63820. else {
  63821. // You can only trigger the action buttons with a joystick declared
  63822. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  63823. this._action();
  63824. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  63825. }
  63826. }
  63827. };
  63828. VirtualJoystick.prototype._onPointerMove = function (e) {
  63829. // If the current pointer is the one associated to the joystick (first touch contact)
  63830. if (this._joystickPointerID == e.pointerId) {
  63831. this._joystickPointerPos.x = e.clientX;
  63832. this._joystickPointerPos.y = e.clientY;
  63833. this._deltaJoystickVector = this._joystickPointerPos.clone();
  63834. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  63835. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  63836. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  63837. switch (this._axisTargetedByLeftAndRight) {
  63838. case JoystickAxis.X:
  63839. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  63840. break;
  63841. case JoystickAxis.Y:
  63842. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  63843. break;
  63844. case JoystickAxis.Z:
  63845. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  63846. break;
  63847. }
  63848. var directionUpDown = this.reverseUpDown ? 1 : -1;
  63849. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  63850. switch (this._axisTargetedByUpAndDown) {
  63851. case JoystickAxis.X:
  63852. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  63853. break;
  63854. case JoystickAxis.Y:
  63855. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  63856. break;
  63857. case JoystickAxis.Z:
  63858. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  63859. break;
  63860. }
  63861. }
  63862. else {
  63863. var data = this._touches.get(e.pointerId.toString());
  63864. if (data) {
  63865. data.x = e.clientX;
  63866. data.y = e.clientY;
  63867. }
  63868. }
  63869. };
  63870. VirtualJoystick.prototype._onPointerUp = function (e) {
  63871. if (this._joystickPointerID == e.pointerId) {
  63872. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  63873. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  63874. this._joystickPointerID = -1;
  63875. this.pressed = false;
  63876. }
  63877. else {
  63878. var touch = this._touches.get(e.pointerId.toString());
  63879. if (touch) {
  63880. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  63881. }
  63882. }
  63883. this._deltaJoystickVector.x = 0;
  63884. this._deltaJoystickVector.y = 0;
  63885. this._touches.remove(e.pointerId.toString());
  63886. };
  63887. /**
  63888. * Change the color of the virtual joystick
  63889. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  63890. */
  63891. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  63892. this._joystickColor = newColor;
  63893. };
  63894. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  63895. this._action = action;
  63896. };
  63897. // Define which axis you'd like to control for left & right
  63898. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  63899. switch (axis) {
  63900. case JoystickAxis.X:
  63901. case JoystickAxis.Y:
  63902. case JoystickAxis.Z:
  63903. this._axisTargetedByLeftAndRight = axis;
  63904. break;
  63905. default:
  63906. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  63907. break;
  63908. }
  63909. };
  63910. // Define which axis you'd like to control for up & down
  63911. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  63912. switch (axis) {
  63913. case JoystickAxis.X:
  63914. case JoystickAxis.Y:
  63915. case JoystickAxis.Z:
  63916. this._axisTargetedByUpAndDown = axis;
  63917. break;
  63918. default:
  63919. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  63920. break;
  63921. }
  63922. };
  63923. VirtualJoystick.prototype._clearCanvas = function () {
  63924. if (this._leftJoystick) {
  63925. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  63926. }
  63927. else {
  63928. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  63929. }
  63930. };
  63931. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  63932. var _this = this;
  63933. if (this.pressed) {
  63934. this._touches.forEach(function (key, touch) {
  63935. if (touch.pointerId === _this._joystickPointerID) {
  63936. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  63937. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  63938. VirtualJoystick.vjCanvasContext.beginPath();
  63939. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  63940. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  63941. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  63942. VirtualJoystick.vjCanvasContext.stroke();
  63943. VirtualJoystick.vjCanvasContext.closePath();
  63944. VirtualJoystick.vjCanvasContext.beginPath();
  63945. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  63946. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  63947. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  63948. VirtualJoystick.vjCanvasContext.stroke();
  63949. VirtualJoystick.vjCanvasContext.closePath();
  63950. VirtualJoystick.vjCanvasContext.beginPath();
  63951. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  63952. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  63953. VirtualJoystick.vjCanvasContext.stroke();
  63954. VirtualJoystick.vjCanvasContext.closePath();
  63955. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  63956. }
  63957. else {
  63958. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  63959. VirtualJoystick.vjCanvasContext.beginPath();
  63960. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  63961. VirtualJoystick.vjCanvasContext.beginPath();
  63962. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  63963. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  63964. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  63965. VirtualJoystick.vjCanvasContext.stroke();
  63966. VirtualJoystick.vjCanvasContext.closePath();
  63967. touch.prevX = touch.x;
  63968. touch.prevY = touch.y;
  63969. }
  63970. ;
  63971. });
  63972. }
  63973. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  63974. };
  63975. VirtualJoystick.prototype.releaseCanvas = function () {
  63976. if (VirtualJoystick.vjCanvas) {
  63977. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  63978. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  63979. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  63980. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  63981. window.removeEventListener("resize", this._onResize);
  63982. document.body.removeChild(VirtualJoystick.vjCanvas);
  63983. VirtualJoystick.vjCanvas = null;
  63984. }
  63985. };
  63986. return VirtualJoystick;
  63987. }());
  63988. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  63989. VirtualJoystick._globalJoystickIndex = 0;
  63990. BABYLON.VirtualJoystick = VirtualJoystick;
  63991. })(BABYLON || (BABYLON = {}));
  63992. //# sourceMappingURL=babylon.virtualJoystick.js.map
  63993. var BABYLON;
  63994. (function (BABYLON) {
  63995. // We're mainly based on the logic defined into the FreeCamera code
  63996. var VirtualJoysticksCamera = (function (_super) {
  63997. __extends(VirtualJoysticksCamera, _super);
  63998. function VirtualJoysticksCamera(name, position, scene) {
  63999. var _this = _super.call(this, name, position, scene) || this;
  64000. _this.inputs.addVirtualJoystick();
  64001. return _this;
  64002. }
  64003. VirtualJoysticksCamera.prototype.getClassName = function () {
  64004. return "VirtualJoysticksCamera";
  64005. };
  64006. return VirtualJoysticksCamera;
  64007. }(BABYLON.FreeCamera));
  64008. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  64009. })(BABYLON || (BABYLON = {}));
  64010. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  64011. var BABYLON;
  64012. (function (BABYLON) {
  64013. var FreeCameraVirtualJoystickInput = (function () {
  64014. function FreeCameraVirtualJoystickInput() {
  64015. }
  64016. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  64017. return this._leftjoystick;
  64018. };
  64019. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  64020. return this._rightjoystick;
  64021. };
  64022. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  64023. if (this._leftjoystick) {
  64024. var camera = this.camera;
  64025. var speed = camera._computeLocalCameraSpeed() * 50;
  64026. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  64027. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  64028. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  64029. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  64030. if (!this._leftjoystick.pressed) {
  64031. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  64032. }
  64033. if (!this._rightjoystick.pressed) {
  64034. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  64035. }
  64036. }
  64037. };
  64038. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  64039. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  64040. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  64041. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  64042. this._leftjoystick.setJoystickSensibility(0.15);
  64043. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  64044. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  64045. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  64046. this._rightjoystick.reverseUpDown = true;
  64047. this._rightjoystick.setJoystickSensibility(0.05);
  64048. this._rightjoystick.setJoystickColor("yellow");
  64049. };
  64050. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  64051. this._leftjoystick.releaseCanvas();
  64052. this._rightjoystick.releaseCanvas();
  64053. };
  64054. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  64055. return "FreeCameraVirtualJoystickInput";
  64056. };
  64057. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  64058. return "virtualJoystick";
  64059. };
  64060. return FreeCameraVirtualJoystickInput;
  64061. }());
  64062. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  64063. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  64064. })(BABYLON || (BABYLON = {}));
  64065. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  64066. var BABYLON;
  64067. (function (BABYLON) {
  64068. var SimplificationSettings = (function () {
  64069. function SimplificationSettings(quality, distance, optimizeMesh) {
  64070. this.quality = quality;
  64071. this.distance = distance;
  64072. this.optimizeMesh = optimizeMesh;
  64073. }
  64074. return SimplificationSettings;
  64075. }());
  64076. BABYLON.SimplificationSettings = SimplificationSettings;
  64077. var SimplificationQueue = (function () {
  64078. function SimplificationQueue() {
  64079. this.running = false;
  64080. this._simplificationArray = [];
  64081. }
  64082. SimplificationQueue.prototype.addTask = function (task) {
  64083. this._simplificationArray.push(task);
  64084. };
  64085. SimplificationQueue.prototype.executeNext = function () {
  64086. var task = this._simplificationArray.pop();
  64087. if (task) {
  64088. this.running = true;
  64089. this.runSimplification(task);
  64090. }
  64091. else {
  64092. this.running = false;
  64093. }
  64094. };
  64095. SimplificationQueue.prototype.runSimplification = function (task) {
  64096. var _this = this;
  64097. if (task.parallelProcessing) {
  64098. //parallel simplifier
  64099. task.settings.forEach(function (setting) {
  64100. var simplifier = _this.getSimplifier(task);
  64101. simplifier.simplify(setting, function (newMesh) {
  64102. task.mesh.addLODLevel(setting.distance, newMesh);
  64103. newMesh.isVisible = true;
  64104. //check if it is the last
  64105. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  64106. //all done, run the success callback.
  64107. task.successCallback();
  64108. }
  64109. _this.executeNext();
  64110. });
  64111. });
  64112. }
  64113. else {
  64114. //single simplifier.
  64115. var simplifier = this.getSimplifier(task);
  64116. var runDecimation = function (setting, callback) {
  64117. simplifier.simplify(setting, function (newMesh) {
  64118. task.mesh.addLODLevel(setting.distance, newMesh);
  64119. newMesh.isVisible = true;
  64120. //run the next quality level
  64121. callback();
  64122. });
  64123. };
  64124. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  64125. runDecimation(task.settings[loop.index], function () {
  64126. loop.executeNext();
  64127. });
  64128. }, function () {
  64129. //execution ended, run the success callback.
  64130. if (task.successCallback) {
  64131. task.successCallback();
  64132. }
  64133. _this.executeNext();
  64134. });
  64135. }
  64136. };
  64137. SimplificationQueue.prototype.getSimplifier = function (task) {
  64138. switch (task.simplificationType) {
  64139. case SimplificationType.QUADRATIC:
  64140. default:
  64141. return new QuadraticErrorSimplification(task.mesh);
  64142. }
  64143. };
  64144. return SimplificationQueue;
  64145. }());
  64146. BABYLON.SimplificationQueue = SimplificationQueue;
  64147. /**
  64148. * The implemented types of simplification.
  64149. * At the moment only Quadratic Error Decimation is implemented.
  64150. */
  64151. var SimplificationType;
  64152. (function (SimplificationType) {
  64153. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  64154. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  64155. var DecimationTriangle = (function () {
  64156. function DecimationTriangle(vertices) {
  64157. this.vertices = vertices;
  64158. this.error = new Array(4);
  64159. this.deleted = false;
  64160. this.isDirty = false;
  64161. this.deletePending = false;
  64162. this.borderFactor = 0;
  64163. }
  64164. return DecimationTriangle;
  64165. }());
  64166. BABYLON.DecimationTriangle = DecimationTriangle;
  64167. var DecimationVertex = (function () {
  64168. function DecimationVertex(position, id) {
  64169. this.position = position;
  64170. this.id = id;
  64171. this.isBorder = true;
  64172. this.q = new QuadraticMatrix();
  64173. this.triangleCount = 0;
  64174. this.triangleStart = 0;
  64175. this.originalOffsets = [];
  64176. }
  64177. DecimationVertex.prototype.updatePosition = function (newPosition) {
  64178. this.position.copyFrom(newPosition);
  64179. };
  64180. return DecimationVertex;
  64181. }());
  64182. BABYLON.DecimationVertex = DecimationVertex;
  64183. var QuadraticMatrix = (function () {
  64184. function QuadraticMatrix(data) {
  64185. this.data = new Array(10);
  64186. for (var i = 0; i < 10; ++i) {
  64187. if (data && data[i]) {
  64188. this.data[i] = data[i];
  64189. }
  64190. else {
  64191. this.data[i] = 0;
  64192. }
  64193. }
  64194. }
  64195. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  64196. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  64197. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  64198. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  64199. return det;
  64200. };
  64201. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  64202. for (var i = 0; i < 10; ++i) {
  64203. this.data[i] += matrix.data[i];
  64204. }
  64205. };
  64206. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  64207. for (var i = 0; i < 10; ++i) {
  64208. this.data[i] += data[i];
  64209. }
  64210. };
  64211. QuadraticMatrix.prototype.add = function (matrix) {
  64212. var m = new QuadraticMatrix();
  64213. for (var i = 0; i < 10; ++i) {
  64214. m.data[i] = this.data[i] + matrix.data[i];
  64215. }
  64216. return m;
  64217. };
  64218. QuadraticMatrix.FromData = function (a, b, c, d) {
  64219. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  64220. };
  64221. //returning an array to avoid garbage collection
  64222. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  64223. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  64224. };
  64225. return QuadraticMatrix;
  64226. }());
  64227. BABYLON.QuadraticMatrix = QuadraticMatrix;
  64228. var Reference = (function () {
  64229. function Reference(vertexId, triangleId) {
  64230. this.vertexId = vertexId;
  64231. this.triangleId = triangleId;
  64232. }
  64233. return Reference;
  64234. }());
  64235. BABYLON.Reference = Reference;
  64236. /**
  64237. * An implementation of the Quadratic Error simplification algorithm.
  64238. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  64239. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  64240. * @author RaananW
  64241. */
  64242. var QuadraticErrorSimplification = (function () {
  64243. function QuadraticErrorSimplification(_mesh) {
  64244. this._mesh = _mesh;
  64245. this.initialized = false;
  64246. this.syncIterations = 5000;
  64247. this.aggressiveness = 7;
  64248. this.decimationIterations = 100;
  64249. this.boundingBoxEpsilon = BABYLON.Epsilon;
  64250. }
  64251. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  64252. var _this = this;
  64253. this.initDecimatedMesh();
  64254. //iterating through the submeshes array, one after the other.
  64255. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  64256. _this.initWithMesh(loop.index, function () {
  64257. _this.runDecimation(settings, loop.index, function () {
  64258. loop.executeNext();
  64259. });
  64260. }, settings.optimizeMesh);
  64261. }, function () {
  64262. setTimeout(function () {
  64263. successCallback(_this._reconstructedMesh);
  64264. }, 0);
  64265. });
  64266. };
  64267. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  64268. var _this = this;
  64269. var gCount = 0;
  64270. triangle.vertices.forEach(function (vertex) {
  64271. var count = 0;
  64272. var vPos = vertex.position;
  64273. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  64274. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  64275. ++count;
  64276. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  64277. ++count;
  64278. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  64279. ++count;
  64280. if (count > 1) {
  64281. ++gCount;
  64282. }
  64283. ;
  64284. });
  64285. if (gCount > 1) {
  64286. console.log(triangle, gCount);
  64287. }
  64288. return gCount > 1;
  64289. };
  64290. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  64291. var _this = this;
  64292. var targetCount = ~~(this.triangles.length * settings.quality);
  64293. var deletedTriangles = 0;
  64294. var triangleCount = this.triangles.length;
  64295. var iterationFunction = function (iteration, callback) {
  64296. setTimeout(function () {
  64297. if (iteration % 5 === 0) {
  64298. _this.updateMesh(iteration === 0);
  64299. }
  64300. for (var i = 0; i < _this.triangles.length; ++i) {
  64301. _this.triangles[i].isDirty = false;
  64302. }
  64303. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  64304. var trianglesIterator = function (i) {
  64305. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  64306. var t = _this.triangles[tIdx];
  64307. if (!t)
  64308. return;
  64309. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  64310. return;
  64311. }
  64312. for (var j = 0; j < 3; ++j) {
  64313. if (t.error[j] < threshold) {
  64314. var deleted0 = [];
  64315. var deleted1 = [];
  64316. var v0 = t.vertices[j];
  64317. var v1 = t.vertices[(j + 1) % 3];
  64318. if (v0.isBorder || v1.isBorder)
  64319. continue;
  64320. var p = BABYLON.Vector3.Zero();
  64321. var n = BABYLON.Vector3.Zero();
  64322. var uv = BABYLON.Vector2.Zero();
  64323. var color = new BABYLON.Color4(0, 0, 0, 1);
  64324. _this.calculateError(v0, v1, p, n, uv, color);
  64325. var delTr = [];
  64326. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  64327. continue;
  64328. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  64329. continue;
  64330. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  64331. continue;
  64332. var uniqueArray = [];
  64333. delTr.forEach(function (deletedT) {
  64334. if (uniqueArray.indexOf(deletedT) === -1) {
  64335. deletedT.deletePending = true;
  64336. uniqueArray.push(deletedT);
  64337. }
  64338. });
  64339. if (uniqueArray.length % 2 !== 0) {
  64340. continue;
  64341. }
  64342. v0.q = v1.q.add(v0.q);
  64343. v0.updatePosition(p);
  64344. var tStart = _this.references.length;
  64345. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  64346. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  64347. var tCount = _this.references.length - tStart;
  64348. if (tCount <= v0.triangleCount) {
  64349. if (tCount) {
  64350. for (var c = 0; c < tCount; c++) {
  64351. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  64352. }
  64353. }
  64354. }
  64355. else {
  64356. v0.triangleStart = tStart;
  64357. }
  64358. v0.triangleCount = tCount;
  64359. break;
  64360. }
  64361. }
  64362. };
  64363. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  64364. }, 0);
  64365. };
  64366. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  64367. if (triangleCount - deletedTriangles <= targetCount)
  64368. loop.breakLoop();
  64369. else {
  64370. iterationFunction(loop.index, function () {
  64371. loop.executeNext();
  64372. });
  64373. }
  64374. }, function () {
  64375. setTimeout(function () {
  64376. //reconstruct this part of the mesh
  64377. _this.reconstructMesh(submeshIndex);
  64378. successCallback();
  64379. }, 0);
  64380. });
  64381. };
  64382. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  64383. var _this = this;
  64384. this.vertices = [];
  64385. this.triangles = [];
  64386. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64387. var indices = this._mesh.getIndices();
  64388. var submesh = this._mesh.subMeshes[submeshIndex];
  64389. var findInVertices = function (positionToSearch) {
  64390. if (optimizeMesh) {
  64391. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  64392. if (_this.vertices[ii].position.equals(positionToSearch)) {
  64393. return _this.vertices[ii];
  64394. }
  64395. }
  64396. }
  64397. return null;
  64398. };
  64399. var vertexReferences = [];
  64400. var vertexInit = function (i) {
  64401. var offset = i + submesh.verticesStart;
  64402. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  64403. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  64404. vertex.originalOffsets.push(offset);
  64405. if (vertex.id === _this.vertices.length) {
  64406. _this.vertices.push(vertex);
  64407. }
  64408. vertexReferences.push(vertex.id);
  64409. };
  64410. //var totalVertices = mesh.getTotalVertices();
  64411. var totalVertices = submesh.verticesCount;
  64412. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  64413. var indicesInit = function (i) {
  64414. var offset = (submesh.indexStart / 3) + i;
  64415. var pos = (offset * 3);
  64416. var i0 = indices[pos + 0];
  64417. var i1 = indices[pos + 1];
  64418. var i2 = indices[pos + 2];
  64419. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  64420. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  64421. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  64422. var triangle = new DecimationTriangle([v0, v1, v2]);
  64423. triangle.originalOffset = pos;
  64424. _this.triangles.push(triangle);
  64425. };
  64426. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  64427. _this.init(callback);
  64428. });
  64429. });
  64430. };
  64431. QuadraticErrorSimplification.prototype.init = function (callback) {
  64432. var _this = this;
  64433. var triangleInit1 = function (i) {
  64434. var t = _this.triangles[i];
  64435. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  64436. for (var j = 0; j < 3; j++) {
  64437. 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))));
  64438. }
  64439. };
  64440. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  64441. var triangleInit2 = function (i) {
  64442. var t = _this.triangles[i];
  64443. for (var j = 0; j < 3; ++j) {
  64444. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  64445. }
  64446. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  64447. };
  64448. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  64449. _this.initialized = true;
  64450. callback();
  64451. });
  64452. });
  64453. };
  64454. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  64455. var newTriangles = [];
  64456. var i;
  64457. for (i = 0; i < this.vertices.length; ++i) {
  64458. this.vertices[i].triangleCount = 0;
  64459. }
  64460. var t;
  64461. var j;
  64462. for (i = 0; i < this.triangles.length; ++i) {
  64463. if (!this.triangles[i].deleted) {
  64464. t = this.triangles[i];
  64465. for (j = 0; j < 3; ++j) {
  64466. t.vertices[j].triangleCount = 1;
  64467. }
  64468. newTriangles.push(t);
  64469. }
  64470. }
  64471. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  64472. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  64473. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  64474. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  64475. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64476. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64477. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64478. var vertexCount = 0;
  64479. for (i = 0; i < this.vertices.length; ++i) {
  64480. var vertex = this.vertices[i];
  64481. vertex.id = vertexCount;
  64482. if (vertex.triangleCount) {
  64483. vertex.originalOffsets.forEach(function (originalOffset) {
  64484. newPositionData.push(vertex.position.x);
  64485. newPositionData.push(vertex.position.y);
  64486. newPositionData.push(vertex.position.z);
  64487. newNormalData.push(normalData[originalOffset * 3]);
  64488. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  64489. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  64490. if (uvs && uvs.length) {
  64491. newUVsData.push(uvs[(originalOffset * 2)]);
  64492. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  64493. }
  64494. else if (colorsData && colorsData.length) {
  64495. newColorsData.push(colorsData[(originalOffset * 4)]);
  64496. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  64497. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  64498. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  64499. }
  64500. ++vertexCount;
  64501. });
  64502. }
  64503. }
  64504. var startingIndex = this._reconstructedMesh.getTotalIndices();
  64505. var startingVertex = this._reconstructedMesh.getTotalVertices();
  64506. var submeshesArray = this._reconstructedMesh.subMeshes;
  64507. this._reconstructedMesh.subMeshes = [];
  64508. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  64509. var originalIndices = this._mesh.getIndices();
  64510. for (i = 0; i < newTriangles.length; ++i) {
  64511. t = newTriangles[i]; //now get the new referencing point for each vertex
  64512. [0, 1, 2].forEach(function (idx) {
  64513. var id = originalIndices[t.originalOffset + idx];
  64514. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  64515. if (offset < 0)
  64516. offset = 0;
  64517. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  64518. });
  64519. }
  64520. //overwriting the old vertex buffers and indices.
  64521. this._reconstructedMesh.setIndices(newIndicesArray);
  64522. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  64523. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  64524. if (newUVsData.length > 0)
  64525. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  64526. if (newColorsData.length > 0)
  64527. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  64528. //create submesh
  64529. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  64530. if (submeshIndex > 0) {
  64531. this._reconstructedMesh.subMeshes = [];
  64532. submeshesArray.forEach(function (submesh) {
  64533. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  64534. });
  64535. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  64536. }
  64537. };
  64538. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  64539. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  64540. this._reconstructedMesh.material = this._mesh.material;
  64541. this._reconstructedMesh.parent = this._mesh.parent;
  64542. this._reconstructedMesh.isVisible = false;
  64543. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  64544. };
  64545. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  64546. for (var i = 0; i < vertex1.triangleCount; ++i) {
  64547. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  64548. if (t.deleted)
  64549. continue;
  64550. var s = this.references[vertex1.triangleStart + i].vertexId;
  64551. var v1 = t.vertices[(s + 1) % 3];
  64552. var v2 = t.vertices[(s + 2) % 3];
  64553. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  64554. deletedArray[i] = true;
  64555. delTr.push(t);
  64556. continue;
  64557. }
  64558. var d1 = v1.position.subtract(point);
  64559. d1 = d1.normalize();
  64560. var d2 = v2.position.subtract(point);
  64561. d2 = d2.normalize();
  64562. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  64563. return true;
  64564. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  64565. deletedArray[i] = false;
  64566. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  64567. return true;
  64568. }
  64569. return false;
  64570. };
  64571. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  64572. var newDeleted = deletedTriangles;
  64573. for (var i = 0; i < vertex.triangleCount; ++i) {
  64574. var ref = this.references[vertex.triangleStart + i];
  64575. var t = this.triangles[ref.triangleId];
  64576. if (t.deleted)
  64577. continue;
  64578. if (deletedArray[i] && t.deletePending) {
  64579. t.deleted = true;
  64580. newDeleted++;
  64581. continue;
  64582. }
  64583. t.vertices[ref.vertexId] = origVertex;
  64584. t.isDirty = true;
  64585. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  64586. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  64587. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  64588. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  64589. this.references.push(ref);
  64590. }
  64591. return newDeleted;
  64592. };
  64593. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  64594. for (var i = 0; i < this.vertices.length; ++i) {
  64595. var vCount = [];
  64596. var vId = [];
  64597. var v = this.vertices[i];
  64598. var j;
  64599. for (j = 0; j < v.triangleCount; ++j) {
  64600. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  64601. for (var ii = 0; ii < 3; ii++) {
  64602. var ofs = 0;
  64603. var vv = triangle.vertices[ii];
  64604. while (ofs < vCount.length) {
  64605. if (vId[ofs] === vv.id)
  64606. break;
  64607. ++ofs;
  64608. }
  64609. if (ofs === vCount.length) {
  64610. vCount.push(1);
  64611. vId.push(vv.id);
  64612. }
  64613. else {
  64614. vCount[ofs]++;
  64615. }
  64616. }
  64617. }
  64618. for (j = 0; j < vCount.length; ++j) {
  64619. if (vCount[j] === 1) {
  64620. this.vertices[vId[j]].isBorder = true;
  64621. }
  64622. else {
  64623. this.vertices[vId[j]].isBorder = false;
  64624. }
  64625. }
  64626. }
  64627. };
  64628. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  64629. if (identifyBorders === void 0) { identifyBorders = false; }
  64630. var i;
  64631. if (!identifyBorders) {
  64632. var newTrianglesVector = [];
  64633. for (i = 0; i < this.triangles.length; ++i) {
  64634. if (!this.triangles[i].deleted) {
  64635. newTrianglesVector.push(this.triangles[i]);
  64636. }
  64637. }
  64638. this.triangles = newTrianglesVector;
  64639. }
  64640. for (i = 0; i < this.vertices.length; ++i) {
  64641. this.vertices[i].triangleCount = 0;
  64642. this.vertices[i].triangleStart = 0;
  64643. }
  64644. var t;
  64645. var j;
  64646. var v;
  64647. for (i = 0; i < this.triangles.length; ++i) {
  64648. t = this.triangles[i];
  64649. for (j = 0; j < 3; ++j) {
  64650. v = t.vertices[j];
  64651. v.triangleCount++;
  64652. }
  64653. }
  64654. var tStart = 0;
  64655. for (i = 0; i < this.vertices.length; ++i) {
  64656. this.vertices[i].triangleStart = tStart;
  64657. tStart += this.vertices[i].triangleCount;
  64658. this.vertices[i].triangleCount = 0;
  64659. }
  64660. var newReferences = new Array(this.triangles.length * 3);
  64661. for (i = 0; i < this.triangles.length; ++i) {
  64662. t = this.triangles[i];
  64663. for (j = 0; j < 3; ++j) {
  64664. v = t.vertices[j];
  64665. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  64666. v.triangleCount++;
  64667. }
  64668. }
  64669. this.references = newReferences;
  64670. if (identifyBorders) {
  64671. this.identifyBorder();
  64672. }
  64673. };
  64674. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  64675. var x = point.x;
  64676. var y = point.y;
  64677. var z = point.z;
  64678. 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
  64679. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  64680. };
  64681. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  64682. var q = vertex1.q.add(vertex2.q);
  64683. var border = vertex1.isBorder && vertex2.isBorder;
  64684. var error = 0;
  64685. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  64686. if (qDet !== 0 && !border) {
  64687. if (!pointResult) {
  64688. pointResult = BABYLON.Vector3.Zero();
  64689. }
  64690. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  64691. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  64692. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  64693. error = this.vertexError(q, pointResult);
  64694. }
  64695. else {
  64696. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  64697. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  64698. var error1 = this.vertexError(q, vertex1.position);
  64699. var error2 = this.vertexError(q, vertex2.position);
  64700. var error3 = this.vertexError(q, p3);
  64701. error = Math.min(error1, error2, error3);
  64702. if (error === error1) {
  64703. if (pointResult) {
  64704. pointResult.copyFrom(vertex1.position);
  64705. }
  64706. }
  64707. else if (error === error2) {
  64708. if (pointResult) {
  64709. pointResult.copyFrom(vertex2.position);
  64710. }
  64711. }
  64712. else {
  64713. if (pointResult) {
  64714. pointResult.copyFrom(p3);
  64715. }
  64716. }
  64717. }
  64718. return error;
  64719. };
  64720. return QuadraticErrorSimplification;
  64721. }());
  64722. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  64723. })(BABYLON || (BABYLON = {}));
  64724. //# sourceMappingURL=babylon.meshSimplification.js.map
  64725. var BABYLON;
  64726. (function (BABYLON) {
  64727. var Internals;
  64728. (function (Internals) {
  64729. var MeshLODLevel = (function () {
  64730. function MeshLODLevel(distance, mesh) {
  64731. this.distance = distance;
  64732. this.mesh = mesh;
  64733. }
  64734. return MeshLODLevel;
  64735. }());
  64736. Internals.MeshLODLevel = MeshLODLevel;
  64737. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64738. })(BABYLON || (BABYLON = {}));
  64739. //# sourceMappingURL=babylon.meshLODLevel.js.map
  64740. var BABYLON;
  64741. (function (BABYLON) {
  64742. // Standard optimizations
  64743. var SceneOptimization = (function () {
  64744. function SceneOptimization(priority) {
  64745. if (priority === void 0) { priority = 0; }
  64746. this.priority = priority;
  64747. this.apply = function (scene) {
  64748. return true; // Return true if everything that can be done was applied
  64749. };
  64750. }
  64751. return SceneOptimization;
  64752. }());
  64753. BABYLON.SceneOptimization = SceneOptimization;
  64754. var TextureOptimization = (function (_super) {
  64755. __extends(TextureOptimization, _super);
  64756. function TextureOptimization(priority, maximumSize) {
  64757. if (priority === void 0) { priority = 0; }
  64758. if (maximumSize === void 0) { maximumSize = 1024; }
  64759. var _this = _super.call(this, priority) || this;
  64760. _this.priority = priority;
  64761. _this.maximumSize = maximumSize;
  64762. _this.apply = function (scene) {
  64763. var allDone = true;
  64764. for (var index = 0; index < scene.textures.length; index++) {
  64765. var texture = scene.textures[index];
  64766. if (!texture.canRescale) {
  64767. continue;
  64768. }
  64769. var currentSize = texture.getSize();
  64770. var maxDimension = Math.max(currentSize.width, currentSize.height);
  64771. if (maxDimension > _this.maximumSize) {
  64772. texture.scale(0.5);
  64773. allDone = false;
  64774. }
  64775. }
  64776. return allDone;
  64777. };
  64778. return _this;
  64779. }
  64780. return TextureOptimization;
  64781. }(SceneOptimization));
  64782. BABYLON.TextureOptimization = TextureOptimization;
  64783. var HardwareScalingOptimization = (function (_super) {
  64784. __extends(HardwareScalingOptimization, _super);
  64785. function HardwareScalingOptimization(priority, maximumScale) {
  64786. if (priority === void 0) { priority = 0; }
  64787. if (maximumScale === void 0) { maximumScale = 2; }
  64788. var _this = _super.call(this, priority) || this;
  64789. _this.priority = priority;
  64790. _this.maximumScale = maximumScale;
  64791. _this._currentScale = 1;
  64792. _this.apply = function (scene) {
  64793. _this._currentScale++;
  64794. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  64795. return _this._currentScale >= _this.maximumScale;
  64796. };
  64797. return _this;
  64798. }
  64799. return HardwareScalingOptimization;
  64800. }(SceneOptimization));
  64801. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  64802. var ShadowsOptimization = (function (_super) {
  64803. __extends(ShadowsOptimization, _super);
  64804. function ShadowsOptimization() {
  64805. var _this = _super !== null && _super.apply(this, arguments) || this;
  64806. _this.apply = function (scene) {
  64807. scene.shadowsEnabled = false;
  64808. return true;
  64809. };
  64810. return _this;
  64811. }
  64812. return ShadowsOptimization;
  64813. }(SceneOptimization));
  64814. BABYLON.ShadowsOptimization = ShadowsOptimization;
  64815. var PostProcessesOptimization = (function (_super) {
  64816. __extends(PostProcessesOptimization, _super);
  64817. function PostProcessesOptimization() {
  64818. var _this = _super !== null && _super.apply(this, arguments) || this;
  64819. _this.apply = function (scene) {
  64820. scene.postProcessesEnabled = false;
  64821. return true;
  64822. };
  64823. return _this;
  64824. }
  64825. return PostProcessesOptimization;
  64826. }(SceneOptimization));
  64827. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  64828. var LensFlaresOptimization = (function (_super) {
  64829. __extends(LensFlaresOptimization, _super);
  64830. function LensFlaresOptimization() {
  64831. var _this = _super !== null && _super.apply(this, arguments) || this;
  64832. _this.apply = function (scene) {
  64833. scene.lensFlaresEnabled = false;
  64834. return true;
  64835. };
  64836. return _this;
  64837. }
  64838. return LensFlaresOptimization;
  64839. }(SceneOptimization));
  64840. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  64841. var ParticlesOptimization = (function (_super) {
  64842. __extends(ParticlesOptimization, _super);
  64843. function ParticlesOptimization() {
  64844. var _this = _super !== null && _super.apply(this, arguments) || this;
  64845. _this.apply = function (scene) {
  64846. scene.particlesEnabled = false;
  64847. return true;
  64848. };
  64849. return _this;
  64850. }
  64851. return ParticlesOptimization;
  64852. }(SceneOptimization));
  64853. BABYLON.ParticlesOptimization = ParticlesOptimization;
  64854. var RenderTargetsOptimization = (function (_super) {
  64855. __extends(RenderTargetsOptimization, _super);
  64856. function RenderTargetsOptimization() {
  64857. var _this = _super !== null && _super.apply(this, arguments) || this;
  64858. _this.apply = function (scene) {
  64859. scene.renderTargetsEnabled = false;
  64860. return true;
  64861. };
  64862. return _this;
  64863. }
  64864. return RenderTargetsOptimization;
  64865. }(SceneOptimization));
  64866. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  64867. var MergeMeshesOptimization = (function (_super) {
  64868. __extends(MergeMeshesOptimization, _super);
  64869. function MergeMeshesOptimization() {
  64870. var _this = _super !== null && _super.apply(this, arguments) || this;
  64871. _this._canBeMerged = function (abstractMesh) {
  64872. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  64873. return false;
  64874. }
  64875. var mesh = abstractMesh;
  64876. if (!mesh.isVisible || !mesh.isEnabled()) {
  64877. return false;
  64878. }
  64879. if (mesh.instances.length > 0) {
  64880. return false;
  64881. }
  64882. if (mesh.skeleton || mesh.hasLODLevels) {
  64883. return false;
  64884. }
  64885. if (mesh.parent) {
  64886. return false;
  64887. }
  64888. return true;
  64889. };
  64890. _this.apply = function (scene, updateSelectionTree) {
  64891. var globalPool = scene.meshes.slice(0);
  64892. var globalLength = globalPool.length;
  64893. for (var index = 0; index < globalLength; index++) {
  64894. var currentPool = new Array();
  64895. var current = globalPool[index];
  64896. // Checks
  64897. if (!_this._canBeMerged(current)) {
  64898. continue;
  64899. }
  64900. currentPool.push(current);
  64901. // Find compatible meshes
  64902. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  64903. var otherMesh = globalPool[subIndex];
  64904. if (!_this._canBeMerged(otherMesh)) {
  64905. continue;
  64906. }
  64907. if (otherMesh.material !== current.material) {
  64908. continue;
  64909. }
  64910. if (otherMesh.checkCollisions !== current.checkCollisions) {
  64911. continue;
  64912. }
  64913. currentPool.push(otherMesh);
  64914. globalLength--;
  64915. globalPool.splice(subIndex, 1);
  64916. subIndex--;
  64917. }
  64918. if (currentPool.length < 2) {
  64919. continue;
  64920. }
  64921. // Merge meshes
  64922. BABYLON.Mesh.MergeMeshes(currentPool);
  64923. }
  64924. if (updateSelectionTree != undefined) {
  64925. if (updateSelectionTree) {
  64926. scene.createOrUpdateSelectionOctree();
  64927. }
  64928. }
  64929. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  64930. scene.createOrUpdateSelectionOctree();
  64931. }
  64932. return true;
  64933. };
  64934. return _this;
  64935. }
  64936. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  64937. get: function () {
  64938. return MergeMeshesOptimization._UpdateSelectionTree;
  64939. },
  64940. set: function (value) {
  64941. MergeMeshesOptimization._UpdateSelectionTree = value;
  64942. },
  64943. enumerable: true,
  64944. configurable: true
  64945. });
  64946. return MergeMeshesOptimization;
  64947. }(SceneOptimization));
  64948. MergeMeshesOptimization._UpdateSelectionTree = false;
  64949. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  64950. // Options
  64951. var SceneOptimizerOptions = (function () {
  64952. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  64953. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  64954. if (trackerDuration === void 0) { trackerDuration = 2000; }
  64955. this.targetFrameRate = targetFrameRate;
  64956. this.trackerDuration = trackerDuration;
  64957. this.optimizations = new Array();
  64958. }
  64959. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  64960. var result = new SceneOptimizerOptions(targetFrameRate);
  64961. var priority = 0;
  64962. result.optimizations.push(new MergeMeshesOptimization(priority));
  64963. result.optimizations.push(new ShadowsOptimization(priority));
  64964. result.optimizations.push(new LensFlaresOptimization(priority));
  64965. // Next priority
  64966. priority++;
  64967. result.optimizations.push(new PostProcessesOptimization(priority));
  64968. result.optimizations.push(new ParticlesOptimization(priority));
  64969. // Next priority
  64970. priority++;
  64971. result.optimizations.push(new TextureOptimization(priority, 1024));
  64972. return result;
  64973. };
  64974. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  64975. var result = new SceneOptimizerOptions(targetFrameRate);
  64976. var priority = 0;
  64977. result.optimizations.push(new MergeMeshesOptimization(priority));
  64978. result.optimizations.push(new ShadowsOptimization(priority));
  64979. result.optimizations.push(new LensFlaresOptimization(priority));
  64980. // Next priority
  64981. priority++;
  64982. result.optimizations.push(new PostProcessesOptimization(priority));
  64983. result.optimizations.push(new ParticlesOptimization(priority));
  64984. // Next priority
  64985. priority++;
  64986. result.optimizations.push(new TextureOptimization(priority, 512));
  64987. // Next priority
  64988. priority++;
  64989. result.optimizations.push(new RenderTargetsOptimization(priority));
  64990. // Next priority
  64991. priority++;
  64992. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  64993. return result;
  64994. };
  64995. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  64996. var result = new SceneOptimizerOptions(targetFrameRate);
  64997. var priority = 0;
  64998. result.optimizations.push(new MergeMeshesOptimization(priority));
  64999. result.optimizations.push(new ShadowsOptimization(priority));
  65000. result.optimizations.push(new LensFlaresOptimization(priority));
  65001. // Next priority
  65002. priority++;
  65003. result.optimizations.push(new PostProcessesOptimization(priority));
  65004. result.optimizations.push(new ParticlesOptimization(priority));
  65005. // Next priority
  65006. priority++;
  65007. result.optimizations.push(new TextureOptimization(priority, 256));
  65008. // Next priority
  65009. priority++;
  65010. result.optimizations.push(new RenderTargetsOptimization(priority));
  65011. // Next priority
  65012. priority++;
  65013. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  65014. return result;
  65015. };
  65016. return SceneOptimizerOptions;
  65017. }());
  65018. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  65019. // Scene optimizer tool
  65020. var SceneOptimizer = (function () {
  65021. function SceneOptimizer() {
  65022. }
  65023. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  65024. // TODO: add an epsilon
  65025. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  65026. if (onSuccess) {
  65027. onSuccess();
  65028. }
  65029. return;
  65030. }
  65031. // Apply current level of optimizations
  65032. var allDone = true;
  65033. var noOptimizationApplied = true;
  65034. for (var index = 0; index < options.optimizations.length; index++) {
  65035. var optimization = options.optimizations[index];
  65036. if (optimization.priority === currentPriorityLevel) {
  65037. noOptimizationApplied = false;
  65038. allDone = allDone && optimization.apply(scene);
  65039. }
  65040. }
  65041. // If no optimization was applied, this is a failure :(
  65042. if (noOptimizationApplied) {
  65043. if (onFailure) {
  65044. onFailure();
  65045. }
  65046. return;
  65047. }
  65048. // If all optimizations were done, move to next level
  65049. if (allDone) {
  65050. currentPriorityLevel++;
  65051. }
  65052. // Let's the system running for a specific amount of time before checking FPS
  65053. scene.executeWhenReady(function () {
  65054. setTimeout(function () {
  65055. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  65056. }, options.trackerDuration);
  65057. });
  65058. };
  65059. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  65060. if (!options) {
  65061. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  65062. }
  65063. // Let's the system running for a specific amount of time before checking FPS
  65064. scene.executeWhenReady(function () {
  65065. setTimeout(function () {
  65066. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  65067. }, options.trackerDuration);
  65068. });
  65069. };
  65070. return SceneOptimizer;
  65071. }());
  65072. BABYLON.SceneOptimizer = SceneOptimizer;
  65073. })(BABYLON || (BABYLON = {}));
  65074. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  65075. var BABYLON;
  65076. (function (BABYLON) {
  65077. var OutlineRenderer = (function () {
  65078. function OutlineRenderer(scene) {
  65079. this.zOffset = 1;
  65080. this._scene = scene;
  65081. }
  65082. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  65083. var _this = this;
  65084. if (useOverlay === void 0) { useOverlay = false; }
  65085. var scene = this._scene;
  65086. var engine = this._scene.getEngine();
  65087. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65088. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  65089. return;
  65090. }
  65091. var mesh = subMesh.getRenderingMesh();
  65092. var material = subMesh.getMaterial();
  65093. engine.enableEffect(this._effect);
  65094. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  65095. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  65096. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65097. // Bones
  65098. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65099. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65100. }
  65101. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65102. // Alpha test
  65103. if (material && material.needAlphaTesting()) {
  65104. var alphaTexture = material.getAlphaTestTexture();
  65105. this._effect.setTexture("diffuseSampler", alphaTexture);
  65106. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65107. }
  65108. engine.setZOffset(-this.zOffset);
  65109. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  65110. engine.setZOffset(0);
  65111. };
  65112. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  65113. var defines = [];
  65114. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  65115. var mesh = subMesh.getMesh();
  65116. var material = subMesh.getMaterial();
  65117. // Alpha test
  65118. if (material && material.needAlphaTesting()) {
  65119. defines.push("#define ALPHATEST");
  65120. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65121. attribs.push(BABYLON.VertexBuffer.UVKind);
  65122. defines.push("#define UV1");
  65123. }
  65124. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65125. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65126. defines.push("#define UV2");
  65127. }
  65128. }
  65129. // Bones
  65130. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65131. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65132. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65133. if (mesh.numBoneInfluencers > 4) {
  65134. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65135. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65136. }
  65137. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65138. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65139. }
  65140. else {
  65141. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65142. }
  65143. // Instances
  65144. if (useInstances) {
  65145. defines.push("#define INSTANCES");
  65146. attribs.push("world0");
  65147. attribs.push("world1");
  65148. attribs.push("world2");
  65149. attribs.push("world3");
  65150. }
  65151. // Get correct effect
  65152. var join = defines.join("\n");
  65153. if (this._cachedDefines !== join) {
  65154. this._cachedDefines = join;
  65155. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  65156. }
  65157. return this._effect.isReady();
  65158. };
  65159. return OutlineRenderer;
  65160. }());
  65161. BABYLON.OutlineRenderer = OutlineRenderer;
  65162. })(BABYLON || (BABYLON = {}));
  65163. //# sourceMappingURL=babylon.outlineRenderer.js.map
  65164. var BABYLON;
  65165. (function (BABYLON) {
  65166. var FaceAdjacencies = (function () {
  65167. function FaceAdjacencies() {
  65168. this.edges = new Array();
  65169. this.edgesConnectedCount = 0;
  65170. }
  65171. return FaceAdjacencies;
  65172. }());
  65173. var EdgesRenderer = (function () {
  65174. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  65175. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  65176. if (epsilon === void 0) { epsilon = 0.95; }
  65177. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  65178. this.edgesWidthScalerForOrthographic = 1000.0;
  65179. this.edgesWidthScalerForPerspective = 50.0;
  65180. this._linesPositions = new Array();
  65181. this._linesNormals = new Array();
  65182. this._linesIndices = new Array();
  65183. this._buffers = {};
  65184. this._checkVerticesInsteadOfIndices = false;
  65185. this._source = source;
  65186. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  65187. this._epsilon = epsilon;
  65188. this._prepareRessources();
  65189. this._generateEdgesLines();
  65190. }
  65191. EdgesRenderer.prototype._prepareRessources = function () {
  65192. if (this._lineShader) {
  65193. return;
  65194. }
  65195. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  65196. attributes: ["position", "normal"],
  65197. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  65198. });
  65199. this._lineShader.disableDepthWrite = true;
  65200. this._lineShader.backFaceCulling = false;
  65201. };
  65202. EdgesRenderer.prototype.dispose = function () {
  65203. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  65204. if (buffer) {
  65205. buffer.dispose();
  65206. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  65207. }
  65208. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  65209. if (buffer) {
  65210. buffer.dispose();
  65211. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  65212. }
  65213. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  65214. this._lineShader.dispose();
  65215. };
  65216. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  65217. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  65218. return 0;
  65219. }
  65220. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  65221. return 1;
  65222. }
  65223. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  65224. return 2;
  65225. }
  65226. return -1;
  65227. };
  65228. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  65229. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  65230. return 0;
  65231. }
  65232. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  65233. return 1;
  65234. }
  65235. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  65236. return 2;
  65237. }
  65238. return -1;
  65239. };
  65240. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  65241. var needToCreateLine;
  65242. if (edge === undefined) {
  65243. needToCreateLine = true;
  65244. }
  65245. else {
  65246. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  65247. needToCreateLine = dotProduct < this._epsilon;
  65248. }
  65249. if (needToCreateLine) {
  65250. var offset = this._linesPositions.length / 3;
  65251. var normal = p0.subtract(p1);
  65252. normal.normalize();
  65253. // Positions
  65254. this._linesPositions.push(p0.x);
  65255. this._linesPositions.push(p0.y);
  65256. this._linesPositions.push(p0.z);
  65257. this._linesPositions.push(p0.x);
  65258. this._linesPositions.push(p0.y);
  65259. this._linesPositions.push(p0.z);
  65260. this._linesPositions.push(p1.x);
  65261. this._linesPositions.push(p1.y);
  65262. this._linesPositions.push(p1.z);
  65263. this._linesPositions.push(p1.x);
  65264. this._linesPositions.push(p1.y);
  65265. this._linesPositions.push(p1.z);
  65266. // Normals
  65267. this._linesNormals.push(p1.x);
  65268. this._linesNormals.push(p1.y);
  65269. this._linesNormals.push(p1.z);
  65270. this._linesNormals.push(-1);
  65271. this._linesNormals.push(p1.x);
  65272. this._linesNormals.push(p1.y);
  65273. this._linesNormals.push(p1.z);
  65274. this._linesNormals.push(1);
  65275. this._linesNormals.push(p0.x);
  65276. this._linesNormals.push(p0.y);
  65277. this._linesNormals.push(p0.z);
  65278. this._linesNormals.push(-1);
  65279. this._linesNormals.push(p0.x);
  65280. this._linesNormals.push(p0.y);
  65281. this._linesNormals.push(p0.z);
  65282. this._linesNormals.push(1);
  65283. // Indices
  65284. this._linesIndices.push(offset);
  65285. this._linesIndices.push(offset + 1);
  65286. this._linesIndices.push(offset + 2);
  65287. this._linesIndices.push(offset);
  65288. this._linesIndices.push(offset + 2);
  65289. this._linesIndices.push(offset + 3);
  65290. }
  65291. };
  65292. EdgesRenderer.prototype._generateEdgesLines = function () {
  65293. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65294. var indices = this._source.getIndices();
  65295. // First let's find adjacencies
  65296. var adjacencies = new Array();
  65297. var faceNormals = new Array();
  65298. var index;
  65299. var faceAdjacencies;
  65300. // Prepare faces
  65301. for (index = 0; index < indices.length; index += 3) {
  65302. faceAdjacencies = new FaceAdjacencies();
  65303. var p0Index = indices[index];
  65304. var p1Index = indices[index + 1];
  65305. var p2Index = indices[index + 2];
  65306. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  65307. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  65308. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  65309. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  65310. faceNormal.normalize();
  65311. faceNormals.push(faceNormal);
  65312. adjacencies.push(faceAdjacencies);
  65313. }
  65314. // Scan
  65315. for (index = 0; index < adjacencies.length; index++) {
  65316. faceAdjacencies = adjacencies[index];
  65317. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  65318. var otherFaceAdjacencies = adjacencies[otherIndex];
  65319. if (faceAdjacencies.edgesConnectedCount === 3) {
  65320. break;
  65321. }
  65322. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  65323. continue;
  65324. }
  65325. var otherP0 = indices[otherIndex * 3];
  65326. var otherP1 = indices[otherIndex * 3 + 1];
  65327. var otherP2 = indices[otherIndex * 3 + 2];
  65328. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  65329. var otherEdgeIndex;
  65330. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  65331. continue;
  65332. }
  65333. switch (edgeIndex) {
  65334. case 0:
  65335. if (this._checkVerticesInsteadOfIndices) {
  65336. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  65337. }
  65338. else {
  65339. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  65340. }
  65341. break;
  65342. case 1:
  65343. if (this._checkVerticesInsteadOfIndices) {
  65344. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  65345. }
  65346. else {
  65347. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  65348. }
  65349. break;
  65350. case 2:
  65351. if (this._checkVerticesInsteadOfIndices) {
  65352. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  65353. }
  65354. else {
  65355. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  65356. }
  65357. break;
  65358. }
  65359. if (otherEdgeIndex === -1) {
  65360. continue;
  65361. }
  65362. faceAdjacencies.edges[edgeIndex] = otherIndex;
  65363. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  65364. faceAdjacencies.edgesConnectedCount++;
  65365. otherFaceAdjacencies.edgesConnectedCount++;
  65366. if (faceAdjacencies.edgesConnectedCount === 3) {
  65367. break;
  65368. }
  65369. }
  65370. }
  65371. }
  65372. // Create lines
  65373. for (index = 0; index < adjacencies.length; index++) {
  65374. // 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
  65375. var current = adjacencies[index];
  65376. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  65377. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  65378. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  65379. }
  65380. // Merge into a single mesh
  65381. var engine = this._source.getScene().getEngine();
  65382. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  65383. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  65384. this._ib = engine.createIndexBuffer(this._linesIndices);
  65385. this._indicesCount = this._linesIndices.length;
  65386. };
  65387. EdgesRenderer.prototype.render = function () {
  65388. if (!this._lineShader.isReady()) {
  65389. return;
  65390. }
  65391. var scene = this._source.getScene();
  65392. var engine = scene.getEngine();
  65393. this._lineShader._preBind();
  65394. // VBOs
  65395. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  65396. scene.resetCachedMaterial();
  65397. this._lineShader.setColor4("color", this._source.edgesColor);
  65398. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  65399. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  65400. }
  65401. else {
  65402. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  65403. }
  65404. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  65405. this._lineShader.bind(this._source.getWorldMatrix());
  65406. // Draw order
  65407. engine.draw(true, 0, this._indicesCount);
  65408. this._lineShader.unbind();
  65409. engine.setDepthWrite(true);
  65410. };
  65411. return EdgesRenderer;
  65412. }());
  65413. BABYLON.EdgesRenderer = EdgesRenderer;
  65414. })(BABYLON || (BABYLON = {}));
  65415. //# sourceMappingURL=babylon.edgesRenderer.js.map
  65416. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  65417. /// <reference path="..\Math\babylon.math.ts" />
  65418. var BABYLON;
  65419. (function (BABYLON) {
  65420. /**
  65421. * Special Glow Blur post process only blurring the alpha channel
  65422. * It enforces keeping the most luminous color in the color channel.
  65423. */
  65424. var GlowBlurPostProcess = (function (_super) {
  65425. __extends(GlowBlurPostProcess, _super);
  65426. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  65427. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65428. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  65429. _this.direction = direction;
  65430. _this.kernel = kernel;
  65431. _this.onApplyObservable.add(function (effect) {
  65432. effect.setFloat2("screenSize", _this.width, _this.height);
  65433. effect.setVector2("direction", _this.direction);
  65434. effect.setFloat("blurWidth", _this.kernel);
  65435. });
  65436. return _this;
  65437. }
  65438. return GlowBlurPostProcess;
  65439. }(BABYLON.PostProcess));
  65440. /**
  65441. * The highlight layer Helps adding a glow effect around a mesh.
  65442. *
  65443. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  65444. * glowy meshes to your scene.
  65445. *
  65446. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  65447. */
  65448. var HighlightLayer = (function () {
  65449. /**
  65450. * Instantiates a new highlight Layer and references it to the scene..
  65451. * @param name The name of the layer
  65452. * @param scene The scene to use the layer in
  65453. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  65454. */
  65455. function HighlightLayer(name, scene, options) {
  65456. this.name = name;
  65457. this._vertexBuffers = {};
  65458. this._mainTextureDesiredSize = { width: 0, height: 0 };
  65459. this._meshes = {};
  65460. this._maxSize = 0;
  65461. this._shouldRender = false;
  65462. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  65463. this._excludedMeshes = {};
  65464. /**
  65465. * Specifies whether or not the inner glow is ACTIVE in the layer.
  65466. */
  65467. this.innerGlow = true;
  65468. /**
  65469. * Specifies whether or not the outer glow is ACTIVE in the layer.
  65470. */
  65471. this.outerGlow = true;
  65472. /**
  65473. * Specifies wether the highlight layer is enabled or not.
  65474. */
  65475. this.isEnabled = true;
  65476. /**
  65477. * An event triggered when the highlight layer has been disposed.
  65478. * @type {BABYLON.Observable}
  65479. */
  65480. this.onDisposeObservable = new BABYLON.Observable();
  65481. /**
  65482. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  65483. * @type {BABYLON.Observable}
  65484. */
  65485. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  65486. /**
  65487. * An event triggered when the highlight layer is being blurred.
  65488. * @type {BABYLON.Observable}
  65489. */
  65490. this.onBeforeBlurObservable = new BABYLON.Observable();
  65491. /**
  65492. * An event triggered when the highlight layer has been blurred.
  65493. * @type {BABYLON.Observable}
  65494. */
  65495. this.onAfterBlurObservable = new BABYLON.Observable();
  65496. /**
  65497. * An event triggered when the glowing blurred texture is being merged in the scene.
  65498. * @type {BABYLON.Observable}
  65499. */
  65500. this.onBeforeComposeObservable = new BABYLON.Observable();
  65501. /**
  65502. * An event triggered when the glowing blurred texture has been merged in the scene.
  65503. * @type {BABYLON.Observable}
  65504. */
  65505. this.onAfterComposeObservable = new BABYLON.Observable();
  65506. /**
  65507. * An event triggered when the highlight layer changes its size.
  65508. * @type {BABYLON.Observable}
  65509. */
  65510. this.onSizeChangedObservable = new BABYLON.Observable();
  65511. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65512. var engine = scene.getEngine();
  65513. this._engine = engine;
  65514. this._maxSize = this._engine.getCaps().maxTextureSize;
  65515. this._scene.highlightLayers.push(this);
  65516. // Warn on stencil.
  65517. if (!this._engine.isStencilEnable) {
  65518. 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 }");
  65519. }
  65520. // Adapt options
  65521. this._options = options || {
  65522. mainTextureRatio: 0.25,
  65523. blurTextureSizeRatio: 0.5,
  65524. blurHorizontalSize: 1,
  65525. blurVerticalSize: 1,
  65526. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  65527. };
  65528. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  65529. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  65530. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  65531. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  65532. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  65533. // VBO
  65534. var vertices = [];
  65535. vertices.push(1, 1);
  65536. vertices.push(-1, 1);
  65537. vertices.push(-1, -1);
  65538. vertices.push(1, -1);
  65539. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65540. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  65541. // Indices
  65542. var indices = [];
  65543. indices.push(0);
  65544. indices.push(1);
  65545. indices.push(2);
  65546. indices.push(0);
  65547. indices.push(2);
  65548. indices.push(3);
  65549. this._indexBuffer = engine.createIndexBuffer(indices);
  65550. // Effect
  65551. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  65552. // Render target
  65553. this.setMainTextureSize();
  65554. // Create Textures and post processes
  65555. this.createTextureAndPostProcesses();
  65556. }
  65557. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  65558. /**
  65559. * Gets the horizontal size of the blur.
  65560. */
  65561. get: function () {
  65562. return this._horizontalBlurPostprocess.kernel;
  65563. },
  65564. /**
  65565. * Specifies the horizontal size of the blur.
  65566. */
  65567. set: function (value) {
  65568. this._horizontalBlurPostprocess.kernel = value;
  65569. },
  65570. enumerable: true,
  65571. configurable: true
  65572. });
  65573. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  65574. /**
  65575. * Gets the vertical size of the blur.
  65576. */
  65577. get: function () {
  65578. return this._verticalBlurPostprocess.kernel;
  65579. },
  65580. /**
  65581. * Specifies the vertical size of the blur.
  65582. */
  65583. set: function (value) {
  65584. this._verticalBlurPostprocess.kernel = value;
  65585. },
  65586. enumerable: true,
  65587. configurable: true
  65588. });
  65589. Object.defineProperty(HighlightLayer.prototype, "camera", {
  65590. /**
  65591. * Gets the camera attached to the layer.
  65592. */
  65593. get: function () {
  65594. return this._options.camera;
  65595. },
  65596. enumerable: true,
  65597. configurable: true
  65598. });
  65599. /**
  65600. * Creates the render target textures and post processes used in the highlight layer.
  65601. */
  65602. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  65603. var _this = this;
  65604. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  65605. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  65606. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  65607. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  65608. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  65609. width: this._mainTextureDesiredSize.width,
  65610. height: this._mainTextureDesiredSize.height
  65611. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65612. this._mainTexture.activeCamera = this._options.camera;
  65613. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65614. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65615. this._mainTexture.anisotropicFilteringLevel = 1;
  65616. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65617. this._mainTexture.renderParticles = false;
  65618. this._mainTexture.renderList = null;
  65619. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  65620. width: blurTextureWidth,
  65621. height: blurTextureHeight
  65622. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65623. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65624. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65625. this._blurTexture.anisotropicFilteringLevel = 16;
  65626. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65627. this._blurTexture.renderParticles = false;
  65628. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65629. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  65630. effect.setTexture("textureSampler", _this._mainTexture);
  65631. });
  65632. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  65633. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65634. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  65635. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65636. });
  65637. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65638. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  65639. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65640. });
  65641. }
  65642. else {
  65643. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65644. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  65645. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65646. });
  65647. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  65648. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  65649. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  65650. });
  65651. }
  65652. this._mainTexture.onAfterUnbindObservable.add(function () {
  65653. _this.onBeforeBlurObservable.notifyObservers(_this);
  65654. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  65655. _this.onAfterBlurObservable.notifyObservers(_this);
  65656. });
  65657. // Custom render function
  65658. var renderSubMesh = function (subMesh) {
  65659. var mesh = subMesh.getRenderingMesh();
  65660. var scene = _this._scene;
  65661. var engine = scene.getEngine();
  65662. // Culling
  65663. engine.setState(subMesh.getMaterial().backFaceCulling);
  65664. // Managing instances
  65665. var batch = mesh._getInstancesRenderList(subMesh._id);
  65666. if (batch.mustReturn) {
  65667. return;
  65668. }
  65669. // Excluded Mesh
  65670. if (_this._excludedMeshes[mesh.uniqueId]) {
  65671. return;
  65672. }
  65673. ;
  65674. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65675. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  65676. var material = subMesh.getMaterial();
  65677. var emissiveTexture = null;
  65678. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  65679. emissiveTexture = material.emissiveTexture;
  65680. }
  65681. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  65682. engine.enableEffect(_this._glowMapGenerationEffect);
  65683. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  65684. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  65685. if (highlightLayerMesh) {
  65686. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  65687. }
  65688. else {
  65689. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  65690. }
  65691. // Alpha test
  65692. if (material && material.needAlphaTesting()) {
  65693. var alphaTexture = material.getAlphaTestTexture();
  65694. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  65695. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65696. }
  65697. // Glow emissive only
  65698. if (emissiveTexture) {
  65699. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  65700. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  65701. }
  65702. // Bones
  65703. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65704. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65705. }
  65706. // Draw
  65707. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  65708. }
  65709. else {
  65710. // Need to reset refresh rate of the shadowMap
  65711. _this._mainTexture.resetRefreshCounter();
  65712. }
  65713. };
  65714. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  65715. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  65716. var index;
  65717. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65718. renderSubMesh(opaqueSubMeshes.data[index]);
  65719. }
  65720. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65721. renderSubMesh(alphaTestSubMeshes.data[index]);
  65722. }
  65723. for (index = 0; index < transparentSubMeshes.length; index++) {
  65724. renderSubMesh(transparentSubMeshes.data[index]);
  65725. }
  65726. };
  65727. this._mainTexture.onClearObservable.add(function (engine) {
  65728. engine.clear(HighlightLayer.neutralColor, true, true, true);
  65729. });
  65730. };
  65731. /**
  65732. * Checks for the readiness of the element composing the layer.
  65733. * @param subMesh the mesh to check for
  65734. * @param useInstances specify wether or not to use instances to render the mesh
  65735. * @param emissiveTexture the associated emissive texture used to generate the glow
  65736. * @return true if ready otherwise, false
  65737. */
  65738. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  65739. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  65740. return false;
  65741. }
  65742. var defines = [];
  65743. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65744. var mesh = subMesh.getMesh();
  65745. var material = subMesh.getMaterial();
  65746. var uv1 = false;
  65747. var uv2 = false;
  65748. // Alpha test
  65749. if (material && material.needAlphaTesting()) {
  65750. var alphaTexture = material.getAlphaTestTexture();
  65751. if (alphaTexture) {
  65752. defines.push("#define ALPHATEST");
  65753. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  65754. alphaTexture.coordinatesIndex === 1) {
  65755. defines.push("#define DIFFUSEUV2");
  65756. uv2 = true;
  65757. }
  65758. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65759. defines.push("#define DIFFUSEUV1");
  65760. uv1 = true;
  65761. }
  65762. }
  65763. }
  65764. // Emissive
  65765. if (emissiveTexture) {
  65766. defines.push("#define EMISSIVE");
  65767. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  65768. emissiveTexture.coordinatesIndex === 1) {
  65769. defines.push("#define EMISSIVEUV2");
  65770. uv2 = true;
  65771. }
  65772. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65773. defines.push("#define EMISSIVEUV1");
  65774. uv1 = true;
  65775. }
  65776. }
  65777. if (uv1) {
  65778. attribs.push(BABYLON.VertexBuffer.UVKind);
  65779. defines.push("#define UV1");
  65780. }
  65781. if (uv2) {
  65782. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65783. defines.push("#define UV2");
  65784. }
  65785. // Bones
  65786. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65787. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65788. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65789. if (mesh.numBoneInfluencers > 4) {
  65790. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65791. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65792. }
  65793. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65794. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65795. }
  65796. else {
  65797. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65798. }
  65799. // Instances
  65800. if (useInstances) {
  65801. defines.push("#define INSTANCES");
  65802. attribs.push("world0");
  65803. attribs.push("world1");
  65804. attribs.push("world2");
  65805. attribs.push("world3");
  65806. }
  65807. // Get correct effect
  65808. var join = defines.join("\n");
  65809. if (this._cachedDefines !== join) {
  65810. this._cachedDefines = join;
  65811. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  65812. }
  65813. return this._glowMapGenerationEffect.isReady();
  65814. };
  65815. /**
  65816. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  65817. */
  65818. HighlightLayer.prototype.render = function () {
  65819. var currentEffect = this._glowMapMergeEffect;
  65820. // Check
  65821. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  65822. return;
  65823. var engine = this._scene.getEngine();
  65824. this.onBeforeComposeObservable.notifyObservers(this);
  65825. // Render
  65826. engine.enableEffect(currentEffect);
  65827. engine.setState(false);
  65828. // Cache
  65829. var previousStencilBuffer = engine.getStencilBuffer();
  65830. var previousStencilFunction = engine.getStencilFunction();
  65831. var previousStencilMask = engine.getStencilMask();
  65832. var previousStencilOperationPass = engine.getStencilOperationPass();
  65833. var previousStencilOperationFail = engine.getStencilOperationFail();
  65834. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  65835. var previousAlphaMode = engine.getAlphaMode();
  65836. // Texture
  65837. currentEffect.setTexture("textureSampler", this._blurTexture);
  65838. // VBOs
  65839. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  65840. // Stencil operations
  65841. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  65842. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  65843. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  65844. // Draw order
  65845. engine.setAlphaMode(this._options.alphaBlendingMode);
  65846. engine.setStencilMask(0x00);
  65847. engine.setStencilBuffer(true);
  65848. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  65849. if (this.outerGlow) {
  65850. currentEffect.setFloat("offset", 0);
  65851. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  65852. engine.draw(true, 0, 6);
  65853. }
  65854. if (this.innerGlow) {
  65855. currentEffect.setFloat("offset", 1);
  65856. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  65857. engine.draw(true, 0, 6);
  65858. }
  65859. // Restore Cache
  65860. engine.setStencilFunction(previousStencilFunction);
  65861. engine.setStencilMask(previousStencilMask);
  65862. engine.setAlphaMode(previousAlphaMode);
  65863. engine.setStencilBuffer(previousStencilBuffer);
  65864. engine.setStencilOperationPass(previousStencilOperationPass);
  65865. engine.setStencilOperationFail(previousStencilOperationFail);
  65866. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  65867. engine._stencilState.reset();
  65868. this.onAfterComposeObservable.notifyObservers(this);
  65869. // Handle size changes.
  65870. var size = this._mainTexture.getSize();
  65871. this.setMainTextureSize();
  65872. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  65873. // Recreate RTT and post processes on size change.
  65874. this.onSizeChangedObservable.notifyObservers(this);
  65875. this.disposeTextureAndPostProcesses();
  65876. this.createTextureAndPostProcesses();
  65877. }
  65878. };
  65879. /**
  65880. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  65881. * @param mesh The mesh to exclude from the highlight layer
  65882. */
  65883. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  65884. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  65885. if (!meshExcluded) {
  65886. this._excludedMeshes[mesh.uniqueId] = {
  65887. mesh: mesh,
  65888. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  65889. mesh.getEngine().setStencilBuffer(false);
  65890. }),
  65891. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  65892. mesh.getEngine().setStencilBuffer(true);
  65893. }),
  65894. };
  65895. }
  65896. };
  65897. /**
  65898. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  65899. * @param mesh The mesh to highlight
  65900. */
  65901. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  65902. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  65903. if (meshExcluded) {
  65904. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  65905. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  65906. }
  65907. this._excludedMeshes[mesh.uniqueId] = undefined;
  65908. };
  65909. /**
  65910. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  65911. * @param mesh The mesh to highlight
  65912. * @param color The color of the highlight
  65913. * @param glowEmissiveOnly Extract the glow from the emissive texture
  65914. */
  65915. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  65916. var _this = this;
  65917. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  65918. var meshHighlight = this._meshes[mesh.uniqueId];
  65919. if (meshHighlight) {
  65920. meshHighlight.color = color;
  65921. }
  65922. else {
  65923. this._meshes[mesh.uniqueId] = {
  65924. mesh: mesh,
  65925. color: color,
  65926. // Lambda required for capture due to Observable this context
  65927. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  65928. if (_this._excludedMeshes[mesh.uniqueId]) {
  65929. _this.defaultStencilReference(mesh);
  65930. }
  65931. else {
  65932. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  65933. }
  65934. }),
  65935. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  65936. glowEmissiveOnly: glowEmissiveOnly
  65937. };
  65938. }
  65939. this._shouldRender = true;
  65940. };
  65941. /**
  65942. * Remove a mesh from the highlight layer in order to make it stop glowing.
  65943. * @param mesh The mesh to highlight
  65944. */
  65945. HighlightLayer.prototype.removeMesh = function (mesh) {
  65946. var meshHighlight = this._meshes[mesh.uniqueId];
  65947. if (meshHighlight) {
  65948. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  65949. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  65950. }
  65951. this._meshes[mesh.uniqueId] = undefined;
  65952. this._shouldRender = false;
  65953. for (var meshHighlightToCheck in this._meshes) {
  65954. if (meshHighlightToCheck) {
  65955. this._shouldRender = true;
  65956. break;
  65957. }
  65958. }
  65959. };
  65960. /**
  65961. * Returns true if the layer contains information to display, otherwise false.
  65962. */
  65963. HighlightLayer.prototype.shouldRender = function () {
  65964. return this.isEnabled && this._shouldRender;
  65965. };
  65966. /**
  65967. * Sets the main texture desired size which is the closest power of two
  65968. * of the engine canvas size.
  65969. */
  65970. HighlightLayer.prototype.setMainTextureSize = function () {
  65971. if (this._options.mainTextureFixedSize) {
  65972. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  65973. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  65974. }
  65975. else {
  65976. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  65977. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  65978. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  65979. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  65980. }
  65981. };
  65982. /**
  65983. * Force the stencil to the normal expected value for none glowing parts
  65984. */
  65985. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  65986. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  65987. };
  65988. /**
  65989. * Dispose only the render target textures and post process.
  65990. */
  65991. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  65992. this._blurTexture.dispose();
  65993. this._mainTexture.dispose();
  65994. this._downSamplePostprocess.dispose();
  65995. this._horizontalBlurPostprocess.dispose();
  65996. this._verticalBlurPostprocess.dispose();
  65997. };
  65998. /**
  65999. * Dispose the highlight layer and free resources.
  66000. */
  66001. HighlightLayer.prototype.dispose = function () {
  66002. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66003. if (vertexBuffer) {
  66004. vertexBuffer.dispose();
  66005. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66006. }
  66007. if (this._indexBuffer) {
  66008. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66009. this._indexBuffer = null;
  66010. }
  66011. // Clean textures and post processes
  66012. this.disposeTextureAndPostProcesses();
  66013. // Clean mesh references
  66014. for (var id in this._meshes) {
  66015. var meshHighlight = this._meshes[id];
  66016. if (meshHighlight && meshHighlight.mesh) {
  66017. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  66018. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  66019. }
  66020. }
  66021. this._meshes = null;
  66022. for (var id in this._excludedMeshes) {
  66023. var meshHighlight = this._excludedMeshes[id];
  66024. if (meshHighlight) {
  66025. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  66026. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  66027. }
  66028. }
  66029. this._excludedMeshes = null;
  66030. // Remove from scene
  66031. var index = this._scene.highlightLayers.indexOf(this, 0);
  66032. if (index > -1) {
  66033. this._scene.highlightLayers.splice(index, 1);
  66034. }
  66035. // Callback
  66036. this.onDisposeObservable.notifyObservers(this);
  66037. this.onDisposeObservable.clear();
  66038. this.onBeforeRenderMainTextureObservable.clear();
  66039. this.onBeforeBlurObservable.clear();
  66040. this.onBeforeComposeObservable.clear();
  66041. this.onAfterComposeObservable.clear();
  66042. this.onSizeChangedObservable.clear();
  66043. };
  66044. return HighlightLayer;
  66045. }());
  66046. /**
  66047. * The neutral color used during the preparation of the glow effect.
  66048. * This is black by default as the blend operation is a blend operation.
  66049. */
  66050. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  66051. /**
  66052. * Stencil value used for glowing meshes.
  66053. */
  66054. HighlightLayer.glowingMeshStencilReference = 0x02;
  66055. /**
  66056. * Stencil value used for the other meshes in the scene.
  66057. */
  66058. HighlightLayer.normalMeshStencilReference = 0x01;
  66059. BABYLON.HighlightLayer = HighlightLayer;
  66060. })(BABYLON || (BABYLON = {}));
  66061. //# sourceMappingURL=babylon.highlightlayer.js.map
  66062. var BABYLON;
  66063. (function (BABYLON) {
  66064. var MeshAssetTask = (function () {
  66065. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  66066. this.name = name;
  66067. this.meshesNames = meshesNames;
  66068. this.rootUrl = rootUrl;
  66069. this.sceneFilename = sceneFilename;
  66070. this.isCompleted = false;
  66071. }
  66072. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66073. var _this = this;
  66074. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  66075. _this.loadedMeshes = meshes;
  66076. _this.loadedParticleSystems = particleSystems;
  66077. _this.loadedSkeletons = skeletons;
  66078. _this.isCompleted = true;
  66079. if (_this.onSuccess) {
  66080. _this.onSuccess(_this);
  66081. }
  66082. onSuccess();
  66083. }, null, function () {
  66084. if (_this.onError) {
  66085. _this.onError(_this);
  66086. }
  66087. onError();
  66088. });
  66089. };
  66090. return MeshAssetTask;
  66091. }());
  66092. BABYLON.MeshAssetTask = MeshAssetTask;
  66093. var TextFileAssetTask = (function () {
  66094. function TextFileAssetTask(name, url) {
  66095. this.name = name;
  66096. this.url = url;
  66097. this.isCompleted = false;
  66098. }
  66099. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66100. var _this = this;
  66101. BABYLON.Tools.LoadFile(this.url, function (data) {
  66102. _this.text = data;
  66103. _this.isCompleted = true;
  66104. if (_this.onSuccess) {
  66105. _this.onSuccess(_this);
  66106. }
  66107. onSuccess();
  66108. }, null, scene.database, false, function () {
  66109. if (_this.onError) {
  66110. _this.onError(_this);
  66111. }
  66112. onError();
  66113. });
  66114. };
  66115. return TextFileAssetTask;
  66116. }());
  66117. BABYLON.TextFileAssetTask = TextFileAssetTask;
  66118. var BinaryFileAssetTask = (function () {
  66119. function BinaryFileAssetTask(name, url) {
  66120. this.name = name;
  66121. this.url = url;
  66122. this.isCompleted = false;
  66123. }
  66124. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66125. var _this = this;
  66126. BABYLON.Tools.LoadFile(this.url, function (data) {
  66127. _this.data = data;
  66128. _this.isCompleted = true;
  66129. if (_this.onSuccess) {
  66130. _this.onSuccess(_this);
  66131. }
  66132. onSuccess();
  66133. }, null, scene.database, true, function () {
  66134. if (_this.onError) {
  66135. _this.onError(_this);
  66136. }
  66137. onError();
  66138. });
  66139. };
  66140. return BinaryFileAssetTask;
  66141. }());
  66142. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  66143. var ImageAssetTask = (function () {
  66144. function ImageAssetTask(name, url) {
  66145. this.name = name;
  66146. this.url = url;
  66147. this.isCompleted = false;
  66148. }
  66149. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66150. var _this = this;
  66151. var img = new Image();
  66152. BABYLON.Tools.SetCorsBehavior(this.url, img);
  66153. img.onload = function () {
  66154. _this.image = img;
  66155. _this.isCompleted = true;
  66156. if (_this.onSuccess) {
  66157. _this.onSuccess(_this);
  66158. }
  66159. onSuccess();
  66160. };
  66161. img.onerror = function () {
  66162. if (_this.onError) {
  66163. _this.onError(_this);
  66164. }
  66165. onError();
  66166. };
  66167. img.src = this.url;
  66168. };
  66169. return ImageAssetTask;
  66170. }());
  66171. BABYLON.ImageAssetTask = ImageAssetTask;
  66172. var TextureAssetTask = (function () {
  66173. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  66174. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66175. this.name = name;
  66176. this.url = url;
  66177. this.noMipmap = noMipmap;
  66178. this.invertY = invertY;
  66179. this.samplingMode = samplingMode;
  66180. this.isCompleted = false;
  66181. }
  66182. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66183. var _this = this;
  66184. var onload = function () {
  66185. _this.isCompleted = true;
  66186. if (_this.onSuccess) {
  66187. _this.onSuccess(_this);
  66188. }
  66189. onSuccess();
  66190. };
  66191. var onerror = function () {
  66192. if (_this.onError) {
  66193. _this.onError(_this);
  66194. }
  66195. onError();
  66196. };
  66197. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  66198. };
  66199. return TextureAssetTask;
  66200. }());
  66201. BABYLON.TextureAssetTask = TextureAssetTask;
  66202. var CubeTextureAssetTask = (function () {
  66203. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  66204. this.name = name;
  66205. this.url = url;
  66206. this.extensions = extensions;
  66207. this.noMipmap = noMipmap;
  66208. this.files = files;
  66209. this.isCompleted = false;
  66210. }
  66211. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66212. var _this = this;
  66213. var onload = function () {
  66214. _this.isCompleted = true;
  66215. if (_this.onSuccess) {
  66216. _this.onSuccess(_this);
  66217. }
  66218. onSuccess();
  66219. };
  66220. var onerror = function () {
  66221. if (_this.onError) {
  66222. _this.onError(_this);
  66223. }
  66224. onError();
  66225. };
  66226. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  66227. };
  66228. return CubeTextureAssetTask;
  66229. }());
  66230. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  66231. var HDRCubeTextureAssetTask = (function () {
  66232. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  66233. if (noMipmap === void 0) { noMipmap = false; }
  66234. if (generateHarmonics === void 0) { generateHarmonics = true; }
  66235. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  66236. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  66237. this.name = name;
  66238. this.url = url;
  66239. this.size = size;
  66240. this.noMipmap = noMipmap;
  66241. this.generateHarmonics = generateHarmonics;
  66242. this.useInGammaSpace = useInGammaSpace;
  66243. this.usePMREMGenerator = usePMREMGenerator;
  66244. this.isCompleted = false;
  66245. }
  66246. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66247. var _this = this;
  66248. var onload = function () {
  66249. _this.isCompleted = true;
  66250. if (_this.onSuccess) {
  66251. _this.onSuccess(_this);
  66252. }
  66253. onSuccess();
  66254. };
  66255. var onerror = function () {
  66256. if (_this.onError) {
  66257. _this.onError(_this);
  66258. }
  66259. onError();
  66260. };
  66261. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  66262. };
  66263. return HDRCubeTextureAssetTask;
  66264. }());
  66265. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  66266. var AssetsManager = (function () {
  66267. function AssetsManager(scene) {
  66268. this.tasks = new Array();
  66269. this.waitingTasksCount = 0;
  66270. this.useDefaultLoadingScreen = true;
  66271. this._scene = scene;
  66272. }
  66273. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  66274. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  66275. this.tasks.push(task);
  66276. return task;
  66277. };
  66278. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  66279. var task = new TextFileAssetTask(taskName, url);
  66280. this.tasks.push(task);
  66281. return task;
  66282. };
  66283. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  66284. var task = new BinaryFileAssetTask(taskName, url);
  66285. this.tasks.push(task);
  66286. return task;
  66287. };
  66288. AssetsManager.prototype.addImageTask = function (taskName, url) {
  66289. var task = new ImageAssetTask(taskName, url);
  66290. this.tasks.push(task);
  66291. return task;
  66292. };
  66293. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  66294. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66295. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  66296. this.tasks.push(task);
  66297. return task;
  66298. };
  66299. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  66300. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  66301. this.tasks.push(task);
  66302. return task;
  66303. };
  66304. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  66305. if (noMipmap === void 0) { noMipmap = false; }
  66306. if (generateHarmonics === void 0) { generateHarmonics = true; }
  66307. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  66308. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  66309. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  66310. this.tasks.push(task);
  66311. return task;
  66312. };
  66313. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  66314. this.waitingTasksCount--;
  66315. if (this.waitingTasksCount === 0) {
  66316. if (this.onFinish) {
  66317. this.onFinish(this.tasks);
  66318. }
  66319. this._scene.getEngine().hideLoadingUI();
  66320. }
  66321. };
  66322. AssetsManager.prototype._runTask = function (task) {
  66323. var _this = this;
  66324. task.run(this._scene, function () {
  66325. if (_this.onTaskSuccess) {
  66326. _this.onTaskSuccess(task);
  66327. }
  66328. _this._decreaseWaitingTasksCount();
  66329. }, function () {
  66330. if (_this.onTaskError) {
  66331. _this.onTaskError(task);
  66332. }
  66333. _this._decreaseWaitingTasksCount();
  66334. });
  66335. };
  66336. AssetsManager.prototype.reset = function () {
  66337. this.tasks = new Array();
  66338. return this;
  66339. };
  66340. AssetsManager.prototype.load = function () {
  66341. this.waitingTasksCount = this.tasks.length;
  66342. if (this.waitingTasksCount === 0) {
  66343. if (this.onFinish) {
  66344. this.onFinish(this.tasks);
  66345. }
  66346. return this;
  66347. }
  66348. if (this.useDefaultLoadingScreen) {
  66349. this._scene.getEngine().displayLoadingUI();
  66350. }
  66351. for (var index = 0; index < this.tasks.length; index++) {
  66352. var task = this.tasks[index];
  66353. this._runTask(task);
  66354. }
  66355. return this;
  66356. };
  66357. return AssetsManager;
  66358. }());
  66359. BABYLON.AssetsManager = AssetsManager;
  66360. })(BABYLON || (BABYLON = {}));
  66361. //# sourceMappingURL=babylon.assetsManager.js.map
  66362. var BABYLON;
  66363. (function (BABYLON) {
  66364. var MapTexture = (function (_super) {
  66365. __extends(MapTexture, _super);
  66366. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  66367. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66368. if (useMipMap === void 0) { useMipMap = false; }
  66369. if (margin === void 0) { margin = 0; }
  66370. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  66371. _this.name = name;
  66372. _this._size = size;
  66373. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66374. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66375. // Create the rectPackMap that will allocate portion of the texture
  66376. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  66377. // Create the texture that will store the content
  66378. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  66379. return _this;
  66380. }
  66381. /**
  66382. * Allocate a rectangle of a given size in the texture map
  66383. * @param size the size of the rectangle to allocation
  66384. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  66385. */
  66386. MapTexture.prototype.allocateRect = function (size) {
  66387. return this._rectPackingMap.addRect(size);
  66388. };
  66389. /**
  66390. * Free a given rectangle from the texture map
  66391. * @param rectInfo the instance corresponding to the rect to free.
  66392. */
  66393. MapTexture.prototype.freeRect = function (rectInfo) {
  66394. if (rectInfo) {
  66395. rectInfo.freeContent();
  66396. }
  66397. };
  66398. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  66399. /**
  66400. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  66401. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  66402. * @returns {}
  66403. */
  66404. get: function () {
  66405. return this._rectPackingMap.freeSpace;
  66406. },
  66407. enumerable: true,
  66408. configurable: true
  66409. });
  66410. /**
  66411. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  66412. * 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.
  66413. * Don't forget to call unbindTexture when you're done rendering
  66414. * @param rect the zone to render to
  66415. * @param clear true to clear the portion's color/depth data
  66416. */
  66417. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  66418. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  66419. };
  66420. /**
  66421. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  66422. * 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.
  66423. * Don't forget to call unbindTexture when you're done rendering
  66424. * @param pos the position into the texture
  66425. * @param size the portion to fit the clip space to
  66426. * @param clear true to clear the portion's color/depth data
  66427. */
  66428. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  66429. var engine = this.getScene().getEngine();
  66430. engine.bindFramebuffer(this._texture);
  66431. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  66432. if (clear) {
  66433. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  66434. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  66435. }
  66436. };
  66437. /**
  66438. * Unbind the texture map from the rendering engine.
  66439. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  66440. * @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.
  66441. */
  66442. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  66443. // Dump ?
  66444. if (dumpForDebug) {
  66445. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  66446. }
  66447. var engine = this.getScene().getEngine();
  66448. if (this._replacedViewport) {
  66449. engine.setViewport(this._replacedViewport);
  66450. this._replacedViewport = null;
  66451. }
  66452. engine.unBindFramebuffer(this._texture);
  66453. };
  66454. Object.defineProperty(MapTexture.prototype, "canRescale", {
  66455. get: function () {
  66456. return false;
  66457. },
  66458. enumerable: true,
  66459. configurable: true
  66460. });
  66461. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  66462. // Anyway, there's not much point to use this method for this kind of texture I guess
  66463. MapTexture.prototype.clone = function () {
  66464. return null;
  66465. };
  66466. return MapTexture;
  66467. }(BABYLON.Texture));
  66468. BABYLON.MapTexture = MapTexture;
  66469. })(BABYLON || (BABYLON = {}));
  66470. //# sourceMappingURL=babylon.mapTexture.js.map
  66471. var BABYLON;
  66472. (function (BABYLON) {
  66473. /**
  66474. * This class describe a rectangle that were added to the map.
  66475. * You have access to its coordinates either in pixel or normalized (UV)
  66476. */
  66477. var PackedRect = (function () {
  66478. function PackedRect(root, parent, pos, size) {
  66479. this._pos = pos;
  66480. this._size = size;
  66481. this._root = root;
  66482. this._parent = parent;
  66483. this._contentSize = null;
  66484. this._bottomNode = null;
  66485. this._leftNode = null;
  66486. this._initialSize = null;
  66487. this._rightNode = null;
  66488. }
  66489. Object.defineProperty(PackedRect.prototype, "pos", {
  66490. /**
  66491. * @returns the position of this node into the map
  66492. */
  66493. get: function () {
  66494. return this._pos;
  66495. },
  66496. enumerable: true,
  66497. configurable: true
  66498. });
  66499. Object.defineProperty(PackedRect.prototype, "contentSize", {
  66500. /**
  66501. * @returns the size of the rectangle this node handles
  66502. */
  66503. get: function () {
  66504. return this._contentSize;
  66505. },
  66506. enumerable: true,
  66507. configurable: true
  66508. });
  66509. /**
  66510. * Retrieve the inner position (considering the margin) and stores it into the res object
  66511. * @param res must be a valid Vector2 that will contain the inner position after this call
  66512. */
  66513. PackedRect.prototype.getInnerPosToRef = function (res) {
  66514. var m = this._root._margin;
  66515. res.x = this._pos.x + m;
  66516. res.y = this._pos.y + m;
  66517. };
  66518. /**
  66519. * Retrieve the inner size (considering the margin) and stores it into the res object
  66520. * @param res must be a valid Size that will contain the inner size after this call
  66521. */
  66522. PackedRect.prototype.getInnerSizeToRef = function (res) {
  66523. var m = this._root._margin;
  66524. res.width = this._contentSize.width - (m * 2);
  66525. res.height = this._contentSize.height - (m * 2);
  66526. };
  66527. Object.defineProperty(PackedRect.prototype, "UVs", {
  66528. /**
  66529. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  66530. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  66531. */
  66532. get: function () {
  66533. if (!this._contentSize) {
  66534. throw new Error("Can't compute UVs for this object because it's nor allocated");
  66535. }
  66536. return this.getUVsForCustomSize(this._contentSize);
  66537. },
  66538. enumerable: true,
  66539. configurable: true
  66540. });
  66541. /**
  66542. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  66543. * and then using only a part of the PackRect.
  66544. * This method will return the UVs for this part by given the custom size of what you really use
  66545. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  66546. */
  66547. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  66548. var mainWidth = this._root._size.width;
  66549. var mainHeight = this._root._size.height;
  66550. var margin = this._root._margin;
  66551. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  66552. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  66553. var uvs = new Array();
  66554. uvs.push(topLeft);
  66555. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  66556. uvs.push(rightBottom);
  66557. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  66558. return uvs;
  66559. };
  66560. /**
  66561. * Free this rectangle from the map.
  66562. * Call this method when you no longer need the rectangle to be in the map.
  66563. */
  66564. PackedRect.prototype.freeContent = function () {
  66565. if (!this.contentSize) {
  66566. return;
  66567. }
  66568. this._contentSize = null;
  66569. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  66570. this.attemptDefrag();
  66571. };
  66572. Object.defineProperty(PackedRect.prototype, "isUsed", {
  66573. get: function () {
  66574. return this._contentSize != null || this._leftNode != null;
  66575. },
  66576. enumerable: true,
  66577. configurable: true
  66578. });
  66579. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  66580. var node = this.findNode(contentSize);
  66581. // Not enough space...
  66582. if (!node) {
  66583. return null;
  66584. }
  66585. node.splitNode(contentSize);
  66586. return node;
  66587. };
  66588. PackedRect.prototype.findNode = function (size) {
  66589. var resNode = null;
  66590. var margin = this._root._margin * 2;
  66591. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  66592. if (this.isUsed) {
  66593. if (this._leftNode) {
  66594. resNode = this._leftNode.findNode(size);
  66595. }
  66596. if (!resNode && this._rightNode) {
  66597. resNode = this._rightNode.findNode(size);
  66598. }
  66599. if (!resNode && this._bottomNode) {
  66600. resNode = this._bottomNode.findNode(size);
  66601. }
  66602. }
  66603. else if (this._initialSize) {
  66604. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  66605. resNode = this;
  66606. }
  66607. else {
  66608. return null;
  66609. }
  66610. }
  66611. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  66612. resNode = this;
  66613. }
  66614. return resNode;
  66615. };
  66616. PackedRect.prototype.splitNode = function (contentSize) {
  66617. var cs = PackedRect.TpsSize;
  66618. var margin = this._root._margin * 2;
  66619. cs.copyFrom(contentSize);
  66620. cs.width += margin;
  66621. cs.height += margin;
  66622. // 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)
  66623. if (!this._contentSize && this._initialSize) {
  66624. this._contentSize = cs.clone();
  66625. 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));
  66626. return this._leftNode.splitNode(contentSize);
  66627. }
  66628. else {
  66629. this._contentSize = cs.clone();
  66630. this._initialSize = cs.clone();
  66631. if (cs.width !== this._size.width) {
  66632. 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));
  66633. }
  66634. if (cs.height !== this._size.height) {
  66635. 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));
  66636. }
  66637. return this;
  66638. }
  66639. };
  66640. PackedRect.prototype.attemptDefrag = function () {
  66641. if (!this.isUsed && this.isRecursiveFree) {
  66642. this.clearNode();
  66643. if (this._parent) {
  66644. this._parent.attemptDefrag();
  66645. }
  66646. }
  66647. };
  66648. PackedRect.prototype.clearNode = function () {
  66649. this._initialSize = null;
  66650. this._rightNode = null;
  66651. this._bottomNode = null;
  66652. };
  66653. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  66654. get: function () {
  66655. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  66656. },
  66657. enumerable: true,
  66658. configurable: true
  66659. });
  66660. PackedRect.prototype.evalFreeSize = function (size) {
  66661. var levelSize = 0;
  66662. if (!this.isUsed) {
  66663. var margin = this._root._margin;
  66664. var is = this._initialSize;
  66665. if (is) {
  66666. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  66667. }
  66668. else {
  66669. var size_1 = this._size;
  66670. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  66671. }
  66672. }
  66673. if (this._rightNode) {
  66674. levelSize += this._rightNode.evalFreeSize(0);
  66675. }
  66676. if (this._bottomNode) {
  66677. levelSize += this._bottomNode.evalFreeSize(0);
  66678. }
  66679. return levelSize + size;
  66680. };
  66681. return PackedRect;
  66682. }());
  66683. PackedRect.TpsSize = BABYLON.Size.Zero();
  66684. BABYLON.PackedRect = PackedRect;
  66685. /**
  66686. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  66687. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  66688. * 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.
  66689. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  66690. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  66691. */
  66692. var RectPackingMap = (function (_super) {
  66693. __extends(RectPackingMap, _super);
  66694. /**
  66695. * Create an instance of the object with a dimension using the given size
  66696. * @param size The dimension of the rectangle that will contain all the sub ones.
  66697. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  66698. */
  66699. function RectPackingMap(size, margin) {
  66700. if (margin === void 0) { margin = 0; }
  66701. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  66702. _this._margin = margin;
  66703. _this._root = _this;
  66704. return _this;
  66705. }
  66706. /**
  66707. * Add a rectangle, finding the best location to store it into the map
  66708. * @param size the dimension of the rectangle to store
  66709. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  66710. */
  66711. RectPackingMap.prototype.addRect = function (size) {
  66712. var node = this.findAndSplitNode(size);
  66713. return node;
  66714. };
  66715. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  66716. /**
  66717. * Return the current space free normalized between [0;1]
  66718. * @returns {}
  66719. */
  66720. get: function () {
  66721. var freeSize = 0;
  66722. freeSize = this.evalFreeSize(freeSize);
  66723. return freeSize / (this._size.width * this._size.height);
  66724. },
  66725. enumerable: true,
  66726. configurable: true
  66727. });
  66728. return RectPackingMap;
  66729. }(PackedRect));
  66730. BABYLON.RectPackingMap = RectPackingMap;
  66731. })(BABYLON || (BABYLON = {}));
  66732. //# sourceMappingURL=babylon.rectPackingMap.js.map
  66733. var BABYLON;
  66734. (function (BABYLON) {
  66735. /**
  66736. * This groups together the common properties used for image processing either in direct forward pass
  66737. * or through post processing effect depending on the use of the image processing pipeline in your scene
  66738. * or not.
  66739. */
  66740. var ImageProcessingConfiguration = (function () {
  66741. function ImageProcessingConfiguration() {
  66742. /**
  66743. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  66744. */
  66745. this.colorCurves = new BABYLON.ColorCurves();
  66746. this._colorCurvesEnabled = false;
  66747. this._colorGradingEnabled = false;
  66748. this._colorGradingWithGreenDepth = false;
  66749. this._colorGradingBGR = false;
  66750. this._exposure = 1.0;
  66751. this._toneMappingEnabled = false;
  66752. this._contrast = 1.0;
  66753. /**
  66754. * Vignette stretch size.
  66755. */
  66756. this.vignetteStretch = 0;
  66757. /**
  66758. * Vignette centre X Offset.
  66759. */
  66760. this.vignetteCentreX = 0;
  66761. /**
  66762. * Vignette centre Y Offset.
  66763. */
  66764. this.vignetteCentreY = 0;
  66765. /**
  66766. * Vignette weight or intensity of the vignette effect.
  66767. */
  66768. this.vignetteWeight = 1.5;
  66769. /**
  66770. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  66771. * if vignetteEnabled is set to true.
  66772. */
  66773. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  66774. /**
  66775. * Camera field of view used by the Vignette effect.
  66776. */
  66777. this.vignetteCameraFov = 0.5;
  66778. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  66779. this._vignetteEnabled = false;
  66780. this._applyByPostProcess = false;
  66781. /**
  66782. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  66783. * @type {BABYLON.Observable}
  66784. */
  66785. this.onUpdateParameters = new BABYLON.Observable();
  66786. }
  66787. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  66788. /**
  66789. * Gets wether the color curves effect is enabled.
  66790. */
  66791. get: function () {
  66792. return this._colorCurvesEnabled;
  66793. },
  66794. /**
  66795. * Sets wether the color curves effect is enabled.
  66796. */
  66797. set: function (value) {
  66798. if (this._colorCurvesEnabled === value) {
  66799. return;
  66800. }
  66801. this._colorCurvesEnabled = value;
  66802. this._updateParameters();
  66803. },
  66804. enumerable: true,
  66805. configurable: true
  66806. });
  66807. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  66808. /**
  66809. * Gets wether the color grading effect is enabled.
  66810. */
  66811. get: function () {
  66812. return this._colorGradingEnabled;
  66813. },
  66814. /**
  66815. * Sets wether the color grading effect is enabled.
  66816. */
  66817. set: function (value) {
  66818. if (this._colorGradingEnabled === value) {
  66819. return;
  66820. }
  66821. this._colorGradingEnabled = value;
  66822. this._updateParameters();
  66823. },
  66824. enumerable: true,
  66825. configurable: true
  66826. });
  66827. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  66828. /**
  66829. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  66830. */
  66831. get: function () {
  66832. return this._colorGradingWithGreenDepth;
  66833. },
  66834. /**
  66835. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  66836. */
  66837. set: function (value) {
  66838. if (this._colorGradingWithGreenDepth === value) {
  66839. return;
  66840. }
  66841. this._colorGradingWithGreenDepth = value;
  66842. this._updateParameters();
  66843. },
  66844. enumerable: true,
  66845. configurable: true
  66846. });
  66847. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  66848. /**
  66849. * Gets wether the color grading texture contains BGR values.
  66850. */
  66851. get: function () {
  66852. return this._colorGradingBGR;
  66853. },
  66854. /**
  66855. * Sets wether the color grading texture contains BGR values.
  66856. */
  66857. set: function (value) {
  66858. if (this._colorGradingBGR === value) {
  66859. return;
  66860. }
  66861. this._colorGradingBGR = value;
  66862. this._updateParameters();
  66863. },
  66864. enumerable: true,
  66865. configurable: true
  66866. });
  66867. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  66868. /**
  66869. * Gets the Exposure used in the effect.
  66870. */
  66871. get: function () {
  66872. return this._exposure;
  66873. },
  66874. /**
  66875. * Sets the Exposure used in the effect.
  66876. */
  66877. set: function (value) {
  66878. if (this._exposure === value) {
  66879. return;
  66880. }
  66881. this._exposure = value;
  66882. this._updateParameters();
  66883. },
  66884. enumerable: true,
  66885. configurable: true
  66886. });
  66887. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  66888. /**
  66889. * Gets wether the tone mapping effect is enabled.
  66890. */
  66891. get: function () {
  66892. return this._toneMappingEnabled;
  66893. },
  66894. /**
  66895. * Sets wether the tone mapping effect is enabled.
  66896. */
  66897. set: function (value) {
  66898. if (this._toneMappingEnabled === value) {
  66899. return;
  66900. }
  66901. this._toneMappingEnabled = value;
  66902. this._updateParameters();
  66903. },
  66904. enumerable: true,
  66905. configurable: true
  66906. });
  66907. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  66908. /**
  66909. * Gets the contrast used in the effect.
  66910. */
  66911. get: function () {
  66912. return this._contrast;
  66913. },
  66914. /**
  66915. * Sets the contrast used in the effect.
  66916. */
  66917. set: function (value) {
  66918. if (this._contrast === value) {
  66919. return;
  66920. }
  66921. this._contrast = value;
  66922. this._updateParameters();
  66923. },
  66924. enumerable: true,
  66925. configurable: true
  66926. });
  66927. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  66928. /**
  66929. * Gets the vignette blend mode allowing different kind of effect.
  66930. */
  66931. get: function () {
  66932. return this._vignetteBlendMode;
  66933. },
  66934. /**
  66935. * Sets the vignette blend mode allowing different kind of effect.
  66936. */
  66937. set: function (value) {
  66938. if (this._vignetteBlendMode === value) {
  66939. return;
  66940. }
  66941. this._vignetteBlendMode = value;
  66942. this._updateParameters();
  66943. },
  66944. enumerable: true,
  66945. configurable: true
  66946. });
  66947. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  66948. /**
  66949. * Gets wether the vignette effect is enabled.
  66950. */
  66951. get: function () {
  66952. return this._vignetteEnabled;
  66953. },
  66954. /**
  66955. * Sets wether the vignette effect is enabled.
  66956. */
  66957. set: function (value) {
  66958. if (this._vignetteEnabled === value) {
  66959. return;
  66960. }
  66961. this._vignetteEnabled = value;
  66962. this._updateParameters();
  66963. },
  66964. enumerable: true,
  66965. configurable: true
  66966. });
  66967. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  66968. /**
  66969. * Gets wether the image processing is applied through a post process or not.
  66970. */
  66971. get: function () {
  66972. return this._applyByPostProcess;
  66973. },
  66974. /**
  66975. * Sets wether the image processing is applied through a post process or not.
  66976. */
  66977. set: function (value) {
  66978. if (this._applyByPostProcess === value) {
  66979. return;
  66980. }
  66981. this._applyByPostProcess = value;
  66982. this._updateParameters();
  66983. },
  66984. enumerable: true,
  66985. configurable: true
  66986. });
  66987. /**
  66988. * Method called each time the image processing information changes requires to recompile the effect.
  66989. */
  66990. ImageProcessingConfiguration.prototype._updateParameters = function () {
  66991. this.onUpdateParameters.notifyObservers(this);
  66992. };
  66993. /**
  66994. * Prepare the list of uniforms associated with the Image Processing effects.
  66995. * @param uniformsList The list of uniforms used in the effect
  66996. * @param defines the list of defines currently in use
  66997. */
  66998. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  66999. if (defines.EXPOSURE) {
  67000. uniforms.push("exposureLinear");
  67001. }
  67002. if (defines.CONTRAST) {
  67003. uniforms.push("contrast");
  67004. }
  67005. if (defines.COLORGRADING) {
  67006. uniforms.push("colorTransformSettings");
  67007. }
  67008. if (defines.VIGNETTE) {
  67009. uniforms.push("vInverseScreenSize");
  67010. uniforms.push("vignetteSettings1");
  67011. uniforms.push("vignetteSettings2");
  67012. }
  67013. if (defines.COLORCURVES) {
  67014. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  67015. }
  67016. };
  67017. /**
  67018. * Prepare the list of samplers associated with the Image Processing effects.
  67019. * @param uniformsList The list of uniforms used in the effect
  67020. * @param defines the list of defines currently in use
  67021. */
  67022. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  67023. if (defines.COLORGRADING) {
  67024. samplersList.push("txColorTransform");
  67025. }
  67026. };
  67027. /**
  67028. * Prepare the list of defines associated to the shader.
  67029. * @param defines the list of defines to complete
  67030. */
  67031. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  67032. defines.VIGNETTE = this.vignetteEnabled;
  67033. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  67034. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  67035. defines.TONEMAPPING = this.toneMappingEnabled;
  67036. defines.CONTRAST = (this.contrast !== 1.0);
  67037. defines.EXPOSURE = (this.exposure !== 1.0);
  67038. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  67039. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  67040. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  67041. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  67042. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  67043. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  67044. };
  67045. /**
  67046. * Returns true if all the image processing information are ready.
  67047. */
  67048. ImageProcessingConfiguration.prototype.isReady = function () {
  67049. // Color Grading texure can not be none blocking.
  67050. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  67051. };
  67052. /**
  67053. * Binds the image processing to the shader.
  67054. * @param effect The effect to bind to
  67055. */
  67056. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  67057. if (aspectRatio === void 0) { aspectRatio = 1; }
  67058. // Color Curves
  67059. if (this._colorCurvesEnabled) {
  67060. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  67061. }
  67062. // Vignette
  67063. if (this._vignetteEnabled) {
  67064. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  67065. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  67066. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  67067. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  67068. var vignetteScaleX = vignetteScaleY * aspectRatio;
  67069. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  67070. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  67071. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  67072. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  67073. var vignettePower = -2.0 * this.vignetteWeight;
  67074. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  67075. }
  67076. // Exposure
  67077. effect.setFloat("exposureLinear", this.exposure);
  67078. // Contrast
  67079. effect.setFloat("contrast", this.contrast);
  67080. // Color transform settings
  67081. if (this.colorGradingTexture) {
  67082. effect.setTexture("txColorTransform", this.colorGradingTexture);
  67083. var textureSize = this.colorGradingTexture.getSize().height;
  67084. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  67085. 0.5 / textureSize, // textureOffset
  67086. textureSize, // textureSize
  67087. this.colorGradingTexture.level // weight
  67088. );
  67089. }
  67090. };
  67091. /**
  67092. * Clones the current image processing instance.
  67093. * @return The cloned image processing
  67094. */
  67095. ImageProcessingConfiguration.prototype.clone = function () {
  67096. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  67097. };
  67098. /**
  67099. * Serializes the current image processing instance to a json representation.
  67100. * @return a JSON representation
  67101. */
  67102. ImageProcessingConfiguration.prototype.serialize = function () {
  67103. return BABYLON.SerializationHelper.Serialize(this);
  67104. };
  67105. /**
  67106. * Parses the image processing from a json representation.
  67107. * @param source the JSON source to parse
  67108. * @return The parsed image processing
  67109. */
  67110. ImageProcessingConfiguration.Parse = function (source) {
  67111. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  67112. };
  67113. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  67114. /**
  67115. * Used to apply the vignette as a mix with the pixel color.
  67116. */
  67117. get: function () {
  67118. return this._VIGNETTEMODE_MULTIPLY;
  67119. },
  67120. enumerable: true,
  67121. configurable: true
  67122. });
  67123. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  67124. /**
  67125. * Used to apply the vignette as a replacement of the pixel color.
  67126. */
  67127. get: function () {
  67128. return this._VIGNETTEMODE_OPAQUE;
  67129. },
  67130. enumerable: true,
  67131. configurable: true
  67132. });
  67133. return ImageProcessingConfiguration;
  67134. }());
  67135. // Static constants associated to the image processing.
  67136. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  67137. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  67138. __decorate([
  67139. BABYLON.serializeAsColorCurves()
  67140. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  67141. __decorate([
  67142. BABYLON.serialize()
  67143. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  67144. __decorate([
  67145. BABYLON.serializeAsTexture()
  67146. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  67147. __decorate([
  67148. BABYLON.serialize()
  67149. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  67150. __decorate([
  67151. BABYLON.serialize()
  67152. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  67153. __decorate([
  67154. BABYLON.serialize()
  67155. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  67156. __decorate([
  67157. BABYLON.serialize()
  67158. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  67159. __decorate([
  67160. BABYLON.serialize()
  67161. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  67162. __decorate([
  67163. BABYLON.serialize()
  67164. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  67165. __decorate([
  67166. BABYLON.serialize()
  67167. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  67168. __decorate([
  67169. BABYLON.serialize()
  67170. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  67171. __decorate([
  67172. BABYLON.serialize()
  67173. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  67174. __decorate([
  67175. BABYLON.serialize()
  67176. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  67177. __decorate([
  67178. BABYLON.serializeAsColor4()
  67179. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  67180. __decorate([
  67181. BABYLON.serialize()
  67182. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  67183. __decorate([
  67184. BABYLON.serialize()
  67185. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  67186. __decorate([
  67187. BABYLON.serialize()
  67188. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  67189. __decorate([
  67190. BABYLON.serialize()
  67191. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  67192. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  67193. })(BABYLON || (BABYLON = {}));
  67194. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  67195. var BABYLON;
  67196. (function (BABYLON) {
  67197. var serializedGeometries = [];
  67198. var serializeGeometry = function (geometry, serializationGeometries) {
  67199. if (serializedGeometries[geometry.id]) {
  67200. return;
  67201. }
  67202. if (geometry.doNotSerialize) {
  67203. return;
  67204. }
  67205. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  67206. serializationGeometries.boxes.push(geometry.serialize());
  67207. }
  67208. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  67209. serializationGeometries.spheres.push(geometry.serialize());
  67210. }
  67211. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  67212. serializationGeometries.cylinders.push(geometry.serialize());
  67213. }
  67214. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  67215. serializationGeometries.toruses.push(geometry.serialize());
  67216. }
  67217. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  67218. serializationGeometries.grounds.push(geometry.serialize());
  67219. }
  67220. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  67221. serializationGeometries.planes.push(geometry.serialize());
  67222. }
  67223. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  67224. serializationGeometries.torusKnots.push(geometry.serialize());
  67225. }
  67226. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  67227. throw new Error("Unknown primitive type");
  67228. }
  67229. else {
  67230. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  67231. }
  67232. serializedGeometries[geometry.id] = true;
  67233. };
  67234. var serializeMesh = function (mesh, serializationScene) {
  67235. var serializationObject = {};
  67236. // Geometry
  67237. var geometry = mesh._geometry;
  67238. if (geometry) {
  67239. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  67240. // 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
  67241. serializeGeometry(geometry, serializationScene.geometries);
  67242. }
  67243. }
  67244. // Custom
  67245. if (mesh.serialize) {
  67246. mesh.serialize(serializationObject);
  67247. }
  67248. return serializationObject;
  67249. };
  67250. var finalizeSingleMesh = function (mesh, serializationObject) {
  67251. //only works if the mesh is already loaded
  67252. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  67253. //serialize material
  67254. if (mesh.material) {
  67255. if (mesh.material instanceof BABYLON.StandardMaterial) {
  67256. serializationObject.materials = serializationObject.materials || [];
  67257. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  67258. serializationObject.materials.push(mesh.material.serialize());
  67259. }
  67260. }
  67261. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  67262. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  67263. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  67264. serializationObject.multiMaterials.push(mesh.material.serialize());
  67265. }
  67266. }
  67267. }
  67268. //serialize geometry
  67269. var geometry = mesh._geometry;
  67270. if (geometry) {
  67271. if (!serializationObject.geometries) {
  67272. serializationObject.geometries = {};
  67273. serializationObject.geometries.boxes = [];
  67274. serializationObject.geometries.spheres = [];
  67275. serializationObject.geometries.cylinders = [];
  67276. serializationObject.geometries.toruses = [];
  67277. serializationObject.geometries.grounds = [];
  67278. serializationObject.geometries.planes = [];
  67279. serializationObject.geometries.torusKnots = [];
  67280. serializationObject.geometries.vertexData = [];
  67281. }
  67282. serializeGeometry(geometry, serializationObject.geometries);
  67283. }
  67284. // Skeletons
  67285. if (mesh.skeleton) {
  67286. serializationObject.skeletons = serializationObject.skeletons || [];
  67287. serializationObject.skeletons.push(mesh.skeleton.serialize());
  67288. }
  67289. //serialize the actual mesh
  67290. serializationObject.meshes = serializationObject.meshes || [];
  67291. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  67292. }
  67293. };
  67294. var SceneSerializer = (function () {
  67295. function SceneSerializer() {
  67296. }
  67297. SceneSerializer.ClearCache = function () {
  67298. serializedGeometries = [];
  67299. };
  67300. SceneSerializer.Serialize = function (scene) {
  67301. var serializationObject = {};
  67302. SceneSerializer.ClearCache();
  67303. // Scene
  67304. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  67305. serializationObject.autoClear = scene.autoClear;
  67306. serializationObject.clearColor = scene.clearColor.asArray();
  67307. serializationObject.ambientColor = scene.ambientColor.asArray();
  67308. serializationObject.gravity = scene.gravity.asArray();
  67309. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  67310. serializationObject.workerCollisions = scene.workerCollisions;
  67311. // Fog
  67312. if (scene.fogMode && scene.fogMode !== 0) {
  67313. serializationObject.fogMode = scene.fogMode;
  67314. serializationObject.fogColor = scene.fogColor.asArray();
  67315. serializationObject.fogStart = scene.fogStart;
  67316. serializationObject.fogEnd = scene.fogEnd;
  67317. serializationObject.fogDensity = scene.fogDensity;
  67318. }
  67319. //Physics
  67320. if (scene.isPhysicsEnabled()) {
  67321. serializationObject.physicsEnabled = true;
  67322. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  67323. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  67324. }
  67325. // Metadata
  67326. if (scene.metadata) {
  67327. serializationObject.metadata = scene.metadata;
  67328. }
  67329. // Morph targets
  67330. serializationObject.morphTargetManagers = [];
  67331. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  67332. var abstractMesh = _a[_i];
  67333. var manager = abstractMesh.morphTargetManager;
  67334. if (manager) {
  67335. serializationObject.morphTargetManagers.push(manager.serialize());
  67336. }
  67337. }
  67338. // Lights
  67339. serializationObject.lights = [];
  67340. var index;
  67341. var light;
  67342. for (index = 0; index < scene.lights.length; index++) {
  67343. light = scene.lights[index];
  67344. if (!light.doNotSerialize) {
  67345. serializationObject.lights.push(light.serialize());
  67346. }
  67347. }
  67348. // Cameras
  67349. serializationObject.cameras = [];
  67350. for (index = 0; index < scene.cameras.length; index++) {
  67351. var camera = scene.cameras[index];
  67352. if (!camera.doNotSerialize) {
  67353. serializationObject.cameras.push(camera.serialize());
  67354. }
  67355. }
  67356. if (scene.activeCamera) {
  67357. serializationObject.activeCameraID = scene.activeCamera.id;
  67358. }
  67359. // Animations
  67360. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  67361. // Materials
  67362. serializationObject.materials = [];
  67363. serializationObject.multiMaterials = [];
  67364. var material;
  67365. for (index = 0; index < scene.materials.length; index++) {
  67366. material = scene.materials[index];
  67367. if (!material.doNotSerialize) {
  67368. serializationObject.materials.push(material.serialize());
  67369. }
  67370. }
  67371. // MultiMaterials
  67372. serializationObject.multiMaterials = [];
  67373. for (index = 0; index < scene.multiMaterials.length; index++) {
  67374. var multiMaterial = scene.multiMaterials[index];
  67375. serializationObject.multiMaterials.push(multiMaterial.serialize());
  67376. }
  67377. // Skeletons
  67378. serializationObject.skeletons = [];
  67379. for (index = 0; index < scene.skeletons.length; index++) {
  67380. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  67381. }
  67382. // Geometries
  67383. serializationObject.geometries = {};
  67384. serializationObject.geometries.boxes = [];
  67385. serializationObject.geometries.spheres = [];
  67386. serializationObject.geometries.cylinders = [];
  67387. serializationObject.geometries.toruses = [];
  67388. serializationObject.geometries.grounds = [];
  67389. serializationObject.geometries.planes = [];
  67390. serializationObject.geometries.torusKnots = [];
  67391. serializationObject.geometries.vertexData = [];
  67392. serializedGeometries = [];
  67393. var geometries = scene.getGeometries();
  67394. for (index = 0; index < geometries.length; index++) {
  67395. var geometry = geometries[index];
  67396. if (geometry.isReady()) {
  67397. serializeGeometry(geometry, serializationObject.geometries);
  67398. }
  67399. }
  67400. // Meshes
  67401. serializationObject.meshes = [];
  67402. for (index = 0; index < scene.meshes.length; index++) {
  67403. var abstractMesh = scene.meshes[index];
  67404. if (abstractMesh instanceof BABYLON.Mesh) {
  67405. var mesh = abstractMesh;
  67406. if (!mesh.doNotSerialize) {
  67407. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  67408. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  67409. }
  67410. }
  67411. }
  67412. }
  67413. // Particles Systems
  67414. serializationObject.particleSystems = [];
  67415. for (index = 0; index < scene.particleSystems.length; index++) {
  67416. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  67417. }
  67418. // Lens flares
  67419. serializationObject.lensFlareSystems = [];
  67420. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  67421. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  67422. }
  67423. // Shadows
  67424. serializationObject.shadowGenerators = [];
  67425. for (index = 0; index < scene.lights.length; index++) {
  67426. light = scene.lights[index];
  67427. var shadowGenerator = light.getShadowGenerator();
  67428. if (shadowGenerator) {
  67429. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  67430. }
  67431. }
  67432. // Action Manager
  67433. if (scene.actionManager) {
  67434. serializationObject.actions = scene.actionManager.serialize("scene");
  67435. }
  67436. // Audio
  67437. serializationObject.sounds = [];
  67438. for (index = 0; index < scene.soundTracks.length; index++) {
  67439. var soundtrack = scene.soundTracks[index];
  67440. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  67441. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  67442. }
  67443. }
  67444. return serializationObject;
  67445. };
  67446. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  67447. if (withParents === void 0) { withParents = false; }
  67448. if (withChildren === void 0) { withChildren = false; }
  67449. var serializationObject = {};
  67450. SceneSerializer.ClearCache();
  67451. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  67452. if (withParents || withChildren) {
  67453. //deliberate for loop! not for each, appended should be processed as well.
  67454. for (var i = 0; i < toSerialize.length; ++i) {
  67455. if (withChildren) {
  67456. toSerialize[i].getDescendants().forEach(function (node) {
  67457. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  67458. toSerialize.push(node);
  67459. }
  67460. });
  67461. }
  67462. //make sure the array doesn't contain the object already
  67463. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  67464. toSerialize.push(toSerialize[i].parent);
  67465. }
  67466. }
  67467. }
  67468. toSerialize.forEach(function (mesh) {
  67469. finalizeSingleMesh(mesh, serializationObject);
  67470. });
  67471. return serializationObject;
  67472. };
  67473. return SceneSerializer;
  67474. }());
  67475. BABYLON.SceneSerializer = SceneSerializer;
  67476. })(BABYLON || (BABYLON = {}));
  67477. //# sourceMappingURL=babylon.sceneSerializer.js.map
  67478. var BABYLON;
  67479. (function (BABYLON) {
  67480. var ReflectionProbe = (function () {
  67481. function ReflectionProbe(name, size, scene, generateMipMaps) {
  67482. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67483. var _this = this;
  67484. this.name = name;
  67485. this._viewMatrix = BABYLON.Matrix.Identity();
  67486. this._target = BABYLON.Vector3.Zero();
  67487. this._add = BABYLON.Vector3.Zero();
  67488. this.invertYAxis = false;
  67489. this.position = BABYLON.Vector3.Zero();
  67490. this._scene = scene;
  67491. this._scene.reflectionProbes.push(this);
  67492. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  67493. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  67494. switch (faceIndex) {
  67495. case 0:
  67496. _this._add.copyFromFloats(1, 0, 0);
  67497. break;
  67498. case 1:
  67499. _this._add.copyFromFloats(-1, 0, 0);
  67500. break;
  67501. case 2:
  67502. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  67503. break;
  67504. case 3:
  67505. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  67506. break;
  67507. case 4:
  67508. _this._add.copyFromFloats(0, 0, 1);
  67509. break;
  67510. case 5:
  67511. _this._add.copyFromFloats(0, 0, -1);
  67512. break;
  67513. }
  67514. if (_this._attachedMesh) {
  67515. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  67516. }
  67517. _this.position.addToRef(_this._add, _this._target);
  67518. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  67519. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  67520. });
  67521. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  67522. scene.updateTransformMatrix(true);
  67523. });
  67524. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  67525. }
  67526. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  67527. get: function () {
  67528. return this._renderTargetTexture.samples;
  67529. },
  67530. set: function (value) {
  67531. this._renderTargetTexture.samples = value;
  67532. },
  67533. enumerable: true,
  67534. configurable: true
  67535. });
  67536. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  67537. get: function () {
  67538. return this._renderTargetTexture.refreshRate;
  67539. },
  67540. set: function (value) {
  67541. this._renderTargetTexture.refreshRate = value;
  67542. },
  67543. enumerable: true,
  67544. configurable: true
  67545. });
  67546. ReflectionProbe.prototype.getScene = function () {
  67547. return this._scene;
  67548. };
  67549. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  67550. get: function () {
  67551. return this._renderTargetTexture;
  67552. },
  67553. enumerable: true,
  67554. configurable: true
  67555. });
  67556. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  67557. get: function () {
  67558. return this._renderTargetTexture.renderList;
  67559. },
  67560. enumerable: true,
  67561. configurable: true
  67562. });
  67563. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  67564. this._attachedMesh = mesh;
  67565. };
  67566. /**
  67567. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  67568. *
  67569. * @param renderingGroupId The rendering group id corresponding to its index
  67570. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  67571. */
  67572. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  67573. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  67574. };
  67575. ReflectionProbe.prototype.dispose = function () {
  67576. var index = this._scene.reflectionProbes.indexOf(this);
  67577. if (index !== -1) {
  67578. // Remove from the scene if found
  67579. this._scene.reflectionProbes.splice(index, 1);
  67580. }
  67581. if (this._renderTargetTexture) {
  67582. this._renderTargetTexture.dispose();
  67583. this._renderTargetTexture = null;
  67584. }
  67585. };
  67586. return ReflectionProbe;
  67587. }());
  67588. BABYLON.ReflectionProbe = ReflectionProbe;
  67589. })(BABYLON || (BABYLON = {}));
  67590. //# sourceMappingURL=babylon.reflectionProbe.js.map
  67591. var BABYLON;
  67592. (function (BABYLON) {
  67593. var Layer = (function () {
  67594. function Layer(name, imgUrl, scene, isBackground, color) {
  67595. this.name = name;
  67596. this.scale = new BABYLON.Vector2(1, 1);
  67597. this.offset = new BABYLON.Vector2(0, 0);
  67598. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  67599. this.layerMask = 0x0FFFFFFF;
  67600. this._vertexBuffers = {};
  67601. // Events
  67602. /**
  67603. * An event triggered when the layer is disposed.
  67604. * @type {BABYLON.Observable}
  67605. */
  67606. this.onDisposeObservable = new BABYLON.Observable();
  67607. /**
  67608. * An event triggered before rendering the scene
  67609. * @type {BABYLON.Observable}
  67610. */
  67611. this.onBeforeRenderObservable = new BABYLON.Observable();
  67612. /**
  67613. * An event triggered after rendering the scene
  67614. * @type {BABYLON.Observable}
  67615. */
  67616. this.onAfterRenderObservable = new BABYLON.Observable();
  67617. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  67618. this.isBackground = isBackground === undefined ? true : isBackground;
  67619. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  67620. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67621. this._scene.layers.push(this);
  67622. var engine = this._scene.getEngine();
  67623. // VBO
  67624. var vertices = [];
  67625. vertices.push(1, 1);
  67626. vertices.push(-1, 1);
  67627. vertices.push(-1, -1);
  67628. vertices.push(1, -1);
  67629. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67630. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  67631. // Indices
  67632. var indices = [];
  67633. indices.push(0);
  67634. indices.push(1);
  67635. indices.push(2);
  67636. indices.push(0);
  67637. indices.push(2);
  67638. indices.push(3);
  67639. this._indexBuffer = engine.createIndexBuffer(indices);
  67640. // Effects
  67641. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  67642. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  67643. }
  67644. Object.defineProperty(Layer.prototype, "onDispose", {
  67645. set: function (callback) {
  67646. if (this._onDisposeObserver) {
  67647. this.onDisposeObservable.remove(this._onDisposeObserver);
  67648. }
  67649. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  67650. },
  67651. enumerable: true,
  67652. configurable: true
  67653. });
  67654. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  67655. set: function (callback) {
  67656. if (this._onBeforeRenderObserver) {
  67657. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67658. }
  67659. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67660. },
  67661. enumerable: true,
  67662. configurable: true
  67663. });
  67664. Object.defineProperty(Layer.prototype, "onAfterRender", {
  67665. set: function (callback) {
  67666. if (this._onAfterRenderObserver) {
  67667. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67668. }
  67669. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67670. },
  67671. enumerable: true,
  67672. configurable: true
  67673. });
  67674. Layer.prototype.render = function () {
  67675. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  67676. // Check
  67677. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  67678. return;
  67679. var engine = this._scene.getEngine();
  67680. this.onBeforeRenderObservable.notifyObservers(this);
  67681. // Render
  67682. engine.enableEffect(currentEffect);
  67683. engine.setState(false);
  67684. // Texture
  67685. currentEffect.setTexture("textureSampler", this.texture);
  67686. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  67687. // Color
  67688. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  67689. // Scale / offset
  67690. currentEffect.setVector2("offset", this.offset);
  67691. currentEffect.setVector2("scale", this.scale);
  67692. // VBOs
  67693. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  67694. // Draw order
  67695. if (!this.alphaTest) {
  67696. engine.setAlphaMode(this.alphaBlendingMode);
  67697. engine.draw(true, 0, 6);
  67698. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67699. }
  67700. else {
  67701. engine.draw(true, 0, 6);
  67702. }
  67703. this.onAfterRenderObservable.notifyObservers(this);
  67704. };
  67705. Layer.prototype.dispose = function () {
  67706. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67707. if (vertexBuffer) {
  67708. vertexBuffer.dispose();
  67709. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67710. }
  67711. if (this._indexBuffer) {
  67712. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67713. this._indexBuffer = null;
  67714. }
  67715. if (this.texture) {
  67716. this.texture.dispose();
  67717. this.texture = null;
  67718. }
  67719. // Remove from scene
  67720. var index = this._scene.layers.indexOf(this);
  67721. this._scene.layers.splice(index, 1);
  67722. // Callback
  67723. this.onDisposeObservable.notifyObservers(this);
  67724. this.onDisposeObservable.clear();
  67725. this.onAfterRenderObservable.clear();
  67726. this.onBeforeRenderObservable.clear();
  67727. };
  67728. return Layer;
  67729. }());
  67730. BABYLON.Layer = Layer;
  67731. })(BABYLON || (BABYLON = {}));
  67732. //# sourceMappingURL=babylon.layer.js.map
  67733. var BABYLON;
  67734. (function (BABYLON) {
  67735. var TextureTools = (function () {
  67736. function TextureTools() {
  67737. }
  67738. /**
  67739. * Uses the GPU to create a copy texture rescaled at a given size
  67740. * @param texture Texture to copy from
  67741. * @param width Desired width
  67742. * @param height Desired height
  67743. * @return Generated texture
  67744. */
  67745. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  67746. if (useBilinearMode === void 0) { useBilinearMode = true; }
  67747. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  67748. var scene = texture.getScene();
  67749. var engine = scene.getEngine();
  67750. rtt.wrapU = texture.wrapU;
  67751. rtt.wrapV = texture.wrapV;
  67752. rtt.uOffset = texture.uOffset;
  67753. rtt.vOffset = texture.vOffset;
  67754. rtt.uScale = texture.uScale;
  67755. rtt.vScale = texture.vScale;
  67756. rtt.uAng = texture.uAng;
  67757. rtt.vAng = texture.vAng;
  67758. rtt.wAng = texture.wAng;
  67759. rtt.coordinatesIndex = texture.coordinatesIndex;
  67760. rtt.level = texture.level;
  67761. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  67762. rtt._texture.isReady = false;
  67763. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67764. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67765. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67766. passPostProcess.getEffect().executeWhenCompiled(function () {
  67767. passPostProcess.onApply = function (effect) {
  67768. effect.setTexture("textureSampler", texture);
  67769. };
  67770. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  67771. engine.unBindFramebuffer(rtt.getInternalTexture());
  67772. rtt.disposeFramebufferObjects();
  67773. passPostProcess.dispose();
  67774. rtt._texture.isReady = true;
  67775. });
  67776. return rtt;
  67777. };
  67778. return TextureTools;
  67779. }());
  67780. BABYLON.TextureTools = TextureTools;
  67781. })(BABYLON || (BABYLON = {}));
  67782. //# sourceMappingURL=babylon.textureTools.js.map
  67783. 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 DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\n#endif\n#ifdef BUMP\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 DIFFUSE\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#ifdef AMBIENT\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#ifdef OPACITY\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#ifdef EMISSIVE\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#ifdef LIGHTMAP\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)\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#ifdef BUMP\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#ifdef BUMP\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\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\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)\nvarying vec2 vSpecularUV;\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=vec3(1.0,1.0,1.0);\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#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 VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#ifdef BUMP\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 ALBEDO\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#ifdef AMBIENT\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#ifdef OPACITY\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#ifdef EMISSIVE\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#ifdef LIGHTMAP\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) || defined(METALLICWORKFLOW) \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#ifdef MICROSURFACEMAP\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#ifdef BUMP\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)\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 vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\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\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-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\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#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 METALLICMAP\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\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(V,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\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n\n#ifdef REFRACTION\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\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#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n\n\n\nfloat NdotV=clamp(dot(normalW,viewDirectionW),0.,1.)+0.00001;\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 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\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#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\nsurfaceRefractionColor*=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*=surfaceReflectivityColor;\nfinalSpecular=max(finalSpecular,0.0);\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=surfaceRefractionColor;\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#ifdef RADIANCEOVERALPHA\nluminanceOverAlpha+=getLuminance(environmentRadiance);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecular);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*alpha,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\nfinalSpecular*vLightingIntensity.x*vLightingIntensity.w +\n#endif\n#ifdef REFLECTION\nfinalRadiance*vLightingIntensity.z +\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*=result.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}","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;\n\nuniform mat4 view;\nuniform mat4 projection;\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;\nvUV=offset;\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(texture(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(texture(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":"#version 300 es\nprecision highp float;\nprecision highp int;\n#include<bones300Declaration>\n#include<instances300Declaration>\nin vec3 position;\nin vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nout vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nin vec2 uv;\n#endif\n#ifdef UV2\nin vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nout vec3 vNormalV;\nout vec4 vViewPos;\n#ifdef POSITION\nout 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":"#version 300 es\nprecision highp float;\nprecision highp int;\nin vec3 vNormalV;\nin vec4 vViewPos;\n#ifdef POSITION\nin vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nin vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nlayout(location=0) out vec4 color0;\nlayout(location=1) out vec4 color1;\n#ifdef POSITION\nlayout(location=2) out vec4 color2;\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ncolor0=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\ncolor1=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ncolor2=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 texture,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(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,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\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}\n","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\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}"};
  67784. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangentUpdated.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangentUpdated.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\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 vec3 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\nvec3 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;\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; \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)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\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 darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\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 min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\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);\n\n\n\n\n\nreturn esm;\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\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.);\n\n\n\n\n\nreturn esm;\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);\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;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\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\nvarying vec2 vBumpUV;\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n#ifdef USERIGHTHANDEDSYSTEM\nbinormal=-binormal;\n#endif\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\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\nnormalW=normalize(normalW*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\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);\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);\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);\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);\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#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \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","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\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;\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#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \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;\n#ifdef REFRACTIONMAP_3D\n#else\nuniform mat4 refractionMatrix;\n#endif\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#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 mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec2 vMicrosurfaceTextureLods;\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 getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\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}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\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 lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\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>=lightAngle)\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}","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};"};
  67785. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  67786. module.exports = BABYLON;
  67787. };